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: unify MCP endpoint and consolidate tools (#788)

Aldino Kemalac9f69a1ea23
diff --git a/.gitignore b/.gitignore
index 38168fe1..a810582f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -43,3 +43,4 @@ docs/superpowers/
# whatsmeow store (legacy path)
src/whatsapp/
+.mcp.json
diff --git a/AGENTS.md b/AGENTS.md
index f1954f86..f44b685f 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -6,7 +6,8 @@ Branch: fix/chatwoot-postgres
## OVERVIEW
-Go WhatsApp Web Multi-Device is a Go 1.25.5 WhatsApp Web API server with REST and MCP SSE modes.
+Go WhatsApp Web Multi-Device is a Go 1.25.5 WhatsApp Web API server. MCP is not a separate mode: the `rest`
+command serves it at `/mcp` (streamable HTTP) whenever `config.McpEnabled` is true.
It uses whatsmeow sessions, Fiber, plain Vue 3 modules, and SQLite-backed chat/session storage by default.
## STRUCTURE
@@ -15,7 +16,7 @@ It uses whatsmeow sessions, Fiber, plain Vue 3 modules, and SQLite-backed chat/s
go-whatsapp-web-multidevice/
|-- src/ # Go module root; run Go commands here
| |-- main.go # go:embed views, then cmd.Execute
-| |-- cmd/ # Cobra root, rest, mcp, global app wiring
+| |-- cmd/ # Cobra root, rest (mounts MCP), global app wiring
| |-- config/ # Mutable package globals bound from flags/env
| |-- domains/ # Interfaces and DTOs; see child AGENTS
| |-- usecase/ # Business orchestration; see child AGENTS
@@ -42,7 +43,7 @@ go-whatsapp-web-multidevice/
| Add message type | `src/domains/send/`, `src/usecase/send.go`, `src/ui/rest/send.go` | REST is primary; MCP support is selective. |
| Add quoted reply support | `src/domains/send/`, `src/usecase/send.go`, `src/views/components/Send*.js` | Optional `reply_message_id`; use device-scoped quote lookup. |
| Add REST endpoint | `src/ui/rest/`, `src/usecase/`, `src/domains/` | Handler parses request, usecase validates/executes, domain owns DTO/interface. |
-| Add MCP tool | `src/ui/mcp/` | Register in `Add*Tools`; resolve a device with `helpers.ContextWithDefaultDevice`. |
+| Add MCP tool | `src/ui/mcp/` | Register in `Add*Tools`; resolve a device with `resolveDeviceContext` (`src/ui/mcp/device.go`). |
| Handle WhatsApp event | `src/infrastructure/whatsapp/event_*.go` | Register the concrete event in `event_handler.go`. |
| Presence behavior | `src/infrastructure/whatsapp/event_handler.go`, `presence_pulse.go`, `src/cmd/helpers.go` | Connect-time and scheduled pulse presence. |
| Add chat storage method | `src/domains/chatstorage/interfaces.go`, `sqlite_repository.go`, `chatstorage_wrapper.go` | Update domain, repository, and wrapper together. |
@@ -72,19 +73,19 @@ go-whatsapp-web-multidevice/
| `NormalizeJIDFromLID` | function | `src/infrastructure/whatsapp/jid_utils.go` | Converts `@lid` JIDs to phone JIDs where whatsmeow can resolve them. |
| `pgimport.Importer` | struct | `src/infrastructure/chatwoot/pgimport/conn.go` | Direct Chatwoot Postgres importer for historical messages. |
| `DeviceMiddleware` | middleware | `src/ui/rest/middleware/device.go` | Resolves `X-Device-Id` or `device_id` and injects device context. |
-| `ContextWithDefaultDevice` | helper | `src/ui/mcp/helpers/context.go` | MCP equivalent of REST device middleware for default/only device. |
+| `resolveDeviceContext` | helper | `src/ui/mcp/device.go` | Resolves the MCP call's device: `device_id` tool argument, else the `X-Device-Id`-derived device from `route.go`'s `HTTPContextFunc`, else error. |
## CONVENTIONS
- Go commands run from `src/`; the repo root is not the Go module root.
- Local runtime paths are relative to process cwd, so direct local runs should start from `src/`.
- Config priority is Cobra flags, then env/Viper, then `.env` loaded from `src/`.
-- REST and MCP share the same app initialization and cannot safely run together against the same whatsmeow state in one process.
-- Process-wide helpers in `cmd/helpers.go` guard auto-reconnect and presence-pulse startup for both REST and MCP.
+- MCP is not a separate process: `rest` mounts it at `/mcp` in the same app initialization, sharing one whatsmeow state.
+- Process-wide helpers in `cmd/helpers.go` guard auto-reconnect and presence-pulse startup for the shared REST+MCP process.
- `domains/` defines DTOs and interfaces. Current contracts expose some whatsmeow and multipart types; follow existing contracts but do not add executable business logic there.
- Usecases validate first, then obtain the device/client from context, then call whatsmeow/storage.
- Device-scoped REST routes must pass `whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c))`.
-- MCP handlers do not receive `X-Device-Id`; they resolve the default/only device via `ContextWithDefaultDevice`.
+- MCP device resolution: `route.go`'s `HTTPContextFunc` resolves the connection's `X-Device-Id` header into context (an empty header resolves the default/only device); `resolveDeviceContext` (`src/ui/mcp/device.go`) lets a per-call `device_id` tool argument override it, else errors.
- Optional boolean filters use `*bool` so nil means "not provided".
- Tests are colocated as `*_test.go`, mostly table-driven with `testify/assert` and occasional `testify/suite`.
- Tests that mutate config, package globals, or background worker state should stay serial and restore state with `defer`.
@@ -103,9 +104,9 @@ go-whatsapp-web-multidevice/
## UNIQUE STYLES
-- Cobra subcommands are registered by `init()` side effects in `cmd/rest.go` and `cmd/mcp.go`.
+- Cobra subcommands are registered by `init()` side effects in `cmd/rest.go`; there is no separate `cmd/mcp.go` — `rest` mounts MCP itself.
- The app uses mutable package globals for config, clients, repositories, and usecases instead of dependency injection from `main`.
-- REST has wider coverage than MCP: REST send has 12 routes; MCP exposes send, query, app, and group tool subsets.
+- MCP exposes 5 consolidated tools (`src/ui/mcp/`) — `whatsapp_send`, `whatsapp_message`, `whatsapp_chat`, `whatsapp_group`, `whatsapp_app` — each dispatching on a `type`/`action` argument, versus one REST route per operation.
- Chat storage migrations are Go string literals in the repository, not external migration files.
- The embedded UI uses Vue 3 from CDN, Fomantic UI modals/toasts, and custom delimiters `[[`, `]]`.
- Release workflows generate GoReleaser YAML into `/tmp`; there is no committed `.goreleaser.yml`.
@@ -117,7 +118,6 @@ go-whatsapp-web-multidevice/
```bash
cd src && go run . rest
-cd src && go run . mcp
cd src && go build -o whatsapp
cd src && go test ./...
cd src && go vet ./...
diff --git a/readme.md b/readme.md
index 904c9b1a..1ac6a876 100644
--- a/readme.md
+++ b/readme.md
@@ -37,6 +37,9 @@ Download:
- for example: `./whatsapp rest` instead of ~~./whatsapp~~
- For MCP mode, you need to run `<binary> mcp`
- for example: `./whatsapp mcp`
+ - **Update**: as of `v9`, MCP is no longer a separate mode — it's served by the REST server at `/mcp` (no
+ standalone `mcp` subcommand). See
+ [MCP Server (Model Context Protocol)](#mcp-server-model-context-protocol) for details and migration notes.
- `v7`
- Starting version 7.x we are using goreleaser to build the binary, so you can download the binary
from [release](https://github.com/aldinokemal/go-whatsapp-web-multidevice/releases/latest)
@@ -367,97 +370,58 @@ If you want to build for Raspberry Pi or other ARM devices without needing a C t
### MCP Server (Model Context Protocol)
-This application can also run as an MCP server, allowing AI agents and tools to interact with WhatsApp through a
-standardized protocol.
+MCP is not a separate mode or process — it's served by the REST server itself. Whenever `./whatsapp rest` is
+running, the MCP endpoint is available at `http://<host>:<port><base-path>/mcp` (default
+`http://localhost:3000/mcp`) using the streamable HTTP transport. Disable it with `MCP_ENABLED=false` or
+`--mcp-enabled=false` (default: enabled).
-1. Clone this repo `git clone https://github.com/aldinokemal/go-whatsapp-web-multidevice`
-2. Open the folder that was cloned via cmd/terminal.
-3. run `cd src`
-4. run `go run . mcp` or build the binary and run `./whatsapp mcp`
-5. The MCP server will start on `http://localhost:8080` by default
+#### Available MCP Tools
-#### MCP Server Options
+There are 5 consolidated tools; agents pick behavior via a `type`/`action` argument instead of one tool per
+operation:
-- `--host localhost` - Set the host for MCP server (default: localhost)
-- `--port 8080` - Set the port for MCP server (default: 8080)
+| Tool | `type` / `action` values |
+|--------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------|
+| `whatsapp_send` | `text`, `image`, `video`, `audio`, `document`, `sticker`, `location`, `contact`, `poll`, `link`, `forward` |
+| `whatsapp_message` | `react`, `edit`, `revoke`, `delete`, `mark_read`, `star`, `unstar`, `download_media` |
+| `whatsapp_chat` | `list_chats`, `list_contacts`, `get_messages`, `archive` |
+| `whatsapp_group` | `create`, `join_with_link`, `leave`, `info`, `participants`, `add_participants`, `remove_participants`, `promote`, `demote`, `invite_link`, `set_name`, `set_topic`, `set_settings`, `join_requests`, `manage_join_requests` |
+| `whatsapp_app` | `status`, `login_qr`, `login_code`, `logout`, `reconnect` |
-#### Available MCP Tools
+#### Device selection
-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
-- `whatsapp_send_video` - Send videos from URLs with captions, compression, view-once, and GIF playback options
-- `whatsapp_send_sticker` - Send stickers with automatic WebP conversion (supports JPG/PNG/GIF)
-- `whatsapp_send_document` - Send document/file messages from URLs
-- `whatsapp_send_audio` - Send audio files from URLs, including voice-note mode
-- `whatsapp_send_poll` - Send WhatsApp polls
-
-##### **📋 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
-- `whatsapp_archive_chat` - Archive or unarchive a chat conversation
-- `whatsapp_react_message` - React to a WhatsApp message
-- `whatsapp_edit_message` - Edit a previously sent WhatsApp message
-- `whatsapp_revoke_message` - Delete a WhatsApp message for everyone
-- `whatsapp_delete_message` - Delete a WhatsApp message for the current account only
-- `whatsapp_mark_as_read` - Mark a WhatsApp message as read
-- `whatsapp_star_message` - Star or unstar a WhatsApp message
-
-##### **👥 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
-
-- SSE endpoint: `http://localhost:8080/sse`
-- Message endpoint: `http://localhost:8080/message`
+For multi-device deployments, the `X-Device-Id` header on the MCP client connection selects the device used by
+every tool call on that connection (falls back to the default device if omitted, same as REST). Any individual
+call can override it with an optional `device_id` argument.
### MCP Configuration
-Make sure you have the MCP server running: `./whatsapp mcp`
-
-For AI tools that support MCP with SSE (like Cursor), add this configuration:
+Point your MCP client at the `/mcp` endpoint. It inherits the REST server's basic auth, so include the same
+`Authorization` header your REST calls use:
```json
{
"mcpServers": {
"whatsapp": {
- "url": "http://localhost:8080/sse"
+ "url": "http://localhost:3000/mcp",
+ "headers": {
+ "Authorization": "Basic dXNlcjpzZWNyZXQ=",
+ "X-Device-Id": "628123456789"
+ }
}
}
}
```
+`headers` is optional: include `Authorization` only when basic auth is configured, and `X-Device-Id` only for
+multi-device setups.
+
+#### Migrating from the standalone MCP mode
+
+- `./whatsapp mcp` → `./whatsapp rest` (MCP is now included automatically)
+- `http://localhost:8080/sse` → `http://localhost:3000/mcp`
+- 40 granular tools → 5 consolidated tools (agents pick actions via the `type`/`action` field)
+
### Production Mode REST (docker)
Using Docker Hub:
@@ -580,8 +544,7 @@ You can fork or edit this source code !
### MCP (Model Context Protocol) API
-- MCP server provides standardized tools for AI agents to interact with WhatsApp
-- Supports Server-Sent Events (SSE) transport
+- Served at `/mcp` by the REST server (streamable HTTP transport) whenever `MCP_ENABLED` is true; with `APP_BASE_PATH` set, the route is `<base-path>/mcp`.
- Available tools are listed in the "Available MCP Tools" section above.
- Compatible with MCP-enabled AI tools and agents
@@ -735,5 +698,3 @@ server's URL (see the gowa-ui readme).
- This project is unofficial and not affiliated with WhatsApp.
- Please use official WhatsApp API to avoid any issues.
-- We only able to run MCP or REST API, this is limitation from whatsmeow library. independent MCP will be available in
- the future.
diff --git a/src/cmd/mcp.go b/src/cmd/mcp.go
deleted file mode 100644
index a165f599..00000000
--- a/src/cmd/mcp.go
+++ /dev/null
@@ -1,81 +0,0 @@
-package cmd
-
-import (
- "fmt"
-
- "github.com/sirupsen/logrus"
-
- "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
- "github.com/aldinokemal/go-whatsapp-web-multidevice/ui/mcp"
- "github.com/aldinokemal/go-whatsapp-web-multidevice/ui/rest/helpers"
- "github.com/mark3labs/mcp-go/server"
- "github.com/spf13/cobra"
-)
-
-// rootCmd represents the base command when called without any subcommands
-var mcpCmd = &cobra.Command{
- Use: "mcp",
- Short: "Start WhatsApp MCP server using SSE",
- Long: `Start a WhatsApp MCP (Model Context Protocol) server using Server-Sent Events (SSE) transport. This allows AI agents to interact with WhatsApp through a standardized protocol.`,
- Run: mcpServer,
-}
-
-func init() {
- rootCmd.AddCommand(mcpCmd)
- mcpCmd.Flags().StringVar(&config.McpPort, "port", "8080", "Port for the SSE MCP server")
- mcpCmd.Flags().StringVar(&config.McpHost, "host", "localhost", "Host for the SSE MCP server")
-}
-
-func mcpServer(_ *cobra.Command, _ []string) {
- // Wire Chatwoot forwarding before connecting WhatsApp: the MCP server runs the
- // same WhatsApp event pipeline as REST, so without the registry every forward
- // would resolve to a nil client and be silently dropped.
- initChatwootForwarding(chatStorageRepo)
-
- // Set auto reconnect to whatsapp server after booting
- go helpers.SetAutoConnectAfterBooting(appUsecase)
-
- // Set auto reconnect checking with a valid client reference
- startAutoReconnectCheckerIfClientAvailable()
-
- // Set daily presence pulse scheduler when enabled
- startPresencePulseSchedulerIfEnabled()
-
- // Create MCP server with capabilities
- mcpServer := server.NewMCPServer(
- "WhatsApp Web Multidevice MCP Server",
- config.AppVersion,
- server.WithToolCapabilities(true),
- server.WithResourceCapabilities(true, true),
- )
-
- // Add all WhatsApp tools
- 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,
- server.WithBaseURL(fmt.Sprintf("http://%s:%s", config.McpHost, config.McpPort)),
- server.WithKeepAlive(true),
- )
-
- // Start the SSE server
- addr := fmt.Sprintf("%s:%s", config.McpHost, config.McpPort)
- logrus.Printf("Starting WhatsApp MCP SSE server on %s", addr)
- logrus.Printf("SSE endpoint: http://%s:%s/sse", config.McpHost, config.McpPort)
- logrus.Printf("Message endpoint: http://%s:%s/message", config.McpHost, config.McpPort)
-
- if err := sseServer.Start(addr); err != nil {
- logrus.Fatalf("Failed to start SSE server: %v", err)
- }
-}
diff --git a/src/cmd/mcp_route_test.go b/src/cmd/mcp_route_test.go
new file mode 100644
index 00000000..4a006754
--- /dev/null
+++ b/src/cmd/mcp_route_test.go
@@ -0,0 +1,145 @@
+package cmd
+
+import (
+ "encoding/json"
+ "io"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ uimcp "github.com/aldinokemal/go-whatsapp-web-multidevice/ui/mcp"
+ "github.com/gofiber/fiber/v3"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func mcpRPC(t *testing.T, app *fiber.App, body string, auth bool) (*httptest.ResponseRecorder, map[string]any) {
+ t.Helper()
+ req := httptest.NewRequest("POST", "/mcp", strings.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Accept", "application/json, text/event-stream")
+ if auth {
+ req.SetBasicAuth("user", "secret")
+ }
+ resp, err := app.Test(req)
+ require.NoError(t, err)
+ defer resp.Body.Close()
+ raw, err := io.ReadAll(resp.Body)
+ require.NoError(t, err)
+
+ rec := httptest.NewRecorder()
+ rec.Code = resp.StatusCode
+
+ var decoded map[string]any
+ if len(raw) > 0 && resp.StatusCode == 200 {
+ // streamable HTTP may answer as JSON or as a single SSE event
+ payload := string(raw)
+ if strings.HasPrefix(payload, "event:") || strings.HasPrefix(payload, "data:") {
+ for _, line := range strings.Split(payload, "\n") {
+ if strings.HasPrefix(line, "data:") {
+ payload = strings.TrimSpace(strings.TrimPrefix(line, "data:"))
+ break
+ }
+ }
+ }
+ require.NoError(t, json.Unmarshal([]byte(payload), &decoded), "body: %s", string(raw))
+ }
+ return rec, decoded
+}
+
+const initializeRPC = `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"test","version":"0"}}}`
+const toolsListRPC = `{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}`
+
+func newMcpTestApp(withAuth bool) *fiber.App {
+ app := fiber.New()
+ if withAuth {
+ app.Use(newBasicAuthMiddleware(map[string]string{"user": "secret"}))
+ }
+ // nil DeviceManager: tools/list never touches devices, and the context
+ // func guards nil. Empty deps: tools/list never calls usecases.
+ uimcp.Register(app, nil, uimcp.Deps{})
+ return app
+}
+
+func TestMcpEndpointListsFiveTools(t *testing.T) {
+ app := newMcpTestApp(false)
+
+ rec, initRes := mcpRPC(t, app, initializeRPC, false)
+ require.Equal(t, 200, rec.Code)
+ require.NotNil(t, initRes["result"])
+
+ rec, listRes := mcpRPC(t, app, toolsListRPC, false)
+ require.Equal(t, 200, rec.Code)
+ result, ok := listRes["result"].(map[string]any)
+ require.True(t, ok, "tools/list result: %v", listRes)
+ tools, ok := result["tools"].([]any)
+ require.True(t, ok)
+ require.Len(t, tools, 5)
+
+ names := map[string]bool{}
+ for _, tl := range tools {
+ names[tl.(map[string]any)["name"].(string)] = true
+ }
+ for _, want := range []string{"whatsapp_send", "whatsapp_message", "whatsapp_chat", "whatsapp_group", "whatsapp_app"} {
+ assert.True(t, names[want], "missing tool %s", want)
+ }
+}
+
+func TestMcpEndpointRequiresBasicAuth(t *testing.T) {
+ app := newMcpTestApp(true)
+
+ rec, _ := mcpRPC(t, app, toolsListRPC, false)
+ assert.Equal(t, 401, rec.Code)
+
+ rec, _ = mcpRPC(t, app, initializeRPC, true)
+ assert.Equal(t, 200, rec.Code)
+}
+
+// TestMcpEndpointGetDoesNotHang guards C1: a GET on /mcp must not reach
+// mcp-go's standalone SSE notification stream, which blocks forever behind
+// the fasthttp adaptor (ctx.Done() only fires on server shutdown, never on
+// client disconnect). Only POST and DELETE are mounted, so GET must come
+// back as a client error without app.Test's default timeout ever tripping.
+func TestMcpEndpointGetDoesNotHang(t *testing.T) {
+ app := newMcpTestApp(false)
+
+ req := httptest.NewRequest("GET", "/mcp", nil)
+ req.Header.Set("Accept", "application/json, text/event-stream")
+ resp, err := app.Test(req)
+ require.NoError(t, err)
+ defer resp.Body.Close()
+
+ assert.True(t, resp.StatusCode == fiber.StatusNotFound || resp.StatusCode == fiber.StatusMethodNotAllowed,
+ "GET /mcp returned %d, want 404 or 405", resp.StatusCode)
+}
+
+// TestMcpToolCallRejectsInvalidArgumentsViaSchema guards I1: with
+// WithInputSchemaValidation enabled, a call missing a conditionally-required
+// field (here: type=text without message) must be rejected by mcp-go's
+// validator before the handler runs. The test app wires uimcp.Deps{} with a
+// nil DeviceManager and nil usecases, so the handler itself would fail on
+// device resolution first ("device identification required...") rather than
+// panic — that generic tool error would make an isError:true assertion pass
+// whether or not validation ran. So this test asserts on the actual
+// validator error text ("input schema validation failed"), which can only
+// appear if WithInputSchemaValidation rejected the call before the handler
+// (and its device check) ever ran; the test must fail if validation is
+// disabled again.
+func TestMcpToolCallRejectsInvalidArgumentsViaSchema(t *testing.T) {
+ app := newMcpTestApp(false)
+
+ const callRPC = `{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"whatsapp_send","arguments":{"type":"text","phone":"628"}}}`
+ rec, res := mcpRPC(t, app, callRPC, false)
+ require.Equal(t, 200, rec.Code)
+
+ result, ok := res["result"].(map[string]any)
+ require.True(t, ok, "tools/call response missing result: %v", res)
+ require.Equal(t, true, result["isError"], "expected schema validation failure to surface as isError:true, got: %v", res)
+
+ content, ok := result["content"].([]any)
+ require.True(t, ok && len(content) > 0, "tools/call error result missing content: %v", res)
+ text, _ := content[0].(map[string]any)["text"].(string)
+ assert.Contains(t, text, "input schema validation failed",
+ "expected mcp-go's validator to reject the missing 'message' field before the handler ran, got: %q", text)
+ assert.Contains(t, text, "message", "expected the validator error to name the missing field, got: %q", text)
+}
diff --git a/src/cmd/rest.go b/src/cmd/rest.go
index d6339dc2..741ebdff 100644
--- a/src/cmd/rest.go
+++ b/src/cmd/rest.go
@@ -16,6 +16,7 @@ import (
"github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/uiasset"
"github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"
"github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
+ uimcp "github.com/aldinokemal/go-whatsapp-web-multidevice/ui/mcp"
"github.com/aldinokemal/go-whatsapp-web-multidevice/ui/rest"
"github.com/aldinokemal/go-whatsapp-web-multidevice/ui/rest/helpers"
"github.com/aldinokemal/go-whatsapp-web-multidevice/ui/rest/middleware"
@@ -137,6 +138,19 @@ func restServer(_ *cobra.Command, _ []string) {
// App info (version, limits) for standalone UIs; no device required
rest.InitRestAppInfo(apiGroup)
+ // MCP endpoint — same usecase instances as REST, so both surfaces share
+ // one whatsmeow session. Sits behind the basic-auth middleware above.
+ if config.McpEnabled {
+ uimcp.Register(apiGroup, dm, uimcp.Deps{
+ App: appUsecase,
+ Send: sendUsecase,
+ Chat: chatUsecase,
+ User: userUsecase,
+ Message: messageUsecase,
+ Group: groupUsecase,
+ })
+ }
+
// Device-scoped operations (header-based)
headerDeviceGroup := apiGroup.Group("", middleware.DeviceMiddleware(dm))
registerDeviceScopedRoutes(headerDeviceGroup)
diff --git a/src/cmd/root.go b/src/cmd/root.go
index 134110ab..3d5aa6f4 100644
--- a/src/cmd/root.go
+++ b/src/cmd/root.go
@@ -113,6 +113,9 @@ func initEnvConfig() {
if viper.GetString("app_ui_enabled") != "" {
config.AppUIEnabled = viper.GetBool("app_ui_enabled")
}
+ if viper.GetString("mcp_enabled") != "" {
+ config.McpEnabled = viper.GetBool("mcp_enabled")
+ }
if viper.GetString("app_ui_auto_update") != "" {
config.AppUIAutoUpdate = viper.GetBool("app_ui_auto_update")
}
@@ -383,6 +386,12 @@ func initFlags() {
config.AppUIAssetSHA256,
`supply-chain pin: only serve the dashboard whose sha256 matches --ui-asset-sha256 <hex> (see the release's .sha256 asset)`,
)
+ rootCmd.PersistentFlags().BoolVarP(
+ &config.McpEnabled,
+ "mcp-enabled", "",
+ config.McpEnabled,
+ `serve the MCP endpoint at /mcp --mcp-enabled <bool>`,
+ )
// Database flags
rootCmd.PersistentFlags().StringVarP(
diff --git a/src/config/settings.go b/src/config/settings.go
index bbbccf0b..03ccc94f 100644
--- a/src/config/settings.go
+++ b/src/config/settings.go
@@ -29,8 +29,9 @@ var (
AppUIGithubToken = "" // optional, raises the GitHub API rate limit
AppUIAssetSHA256 = "" // optional supply-chain pin: only serve the asset with this sha256
- McpPort = "8080"
- McpHost = "localhost"
+ // MCP (Model Context Protocol) endpoint, served at {AppBasePath}/mcp on
+ // the REST server. Streamable HTTP transport; inherits basic auth.
+ McpEnabled = true
PathQrCode = "statics/qrcode"
PathSendItems = "statics/senditems"
diff --git a/src/go.mod b/src/go.mod
index d56c50ff..40e9932c 100644
--- a/src/go.mod
+++ b/src/go.mod
@@ -15,6 +15,7 @@ require (
github.com/lib/pq v1.12.3
github.com/mark3labs/mcp-go v0.56.0
github.com/mattn/go-sqlite3 v1.14.48
+ github.com/santhosh-tekuri/jsonschema/v6 v6.0.2
github.com/sirupsen/logrus v1.9.4
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e
github.com/spf13/cobra v1.10.2
@@ -54,7 +55,6 @@ require (
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/rs/zerolog v1.35.1 // indirect
github.com/sagikazarmark/locafero v0.12.0 // indirect
- github.com/santhosh-tekuri/jsonschema/v6 v6.0.2 // indirect
github.com/savsgio/gotils v0.0.0-20250924091648-bce9a52d7761 // indirect
github.com/spf13/afero v1.15.0 // indirect
github.com/spf13/cast v1.10.0 // indirect
diff --git a/src/ui/AGENTS.md b/src/ui/AGENTS.md
index 1714388d..603d574b 100644
--- a/src/ui/AGENTS.md
+++ b/src/ui/AGENTS.md
@@ -4,14 +4,14 @@ Generated: 2026-06-06
## OVERVIEW
-`ui/` adapts HTTP REST, MCP SSE tools, and websockets to domain usecases. It should parse transport payloads and delegate behavior.
+`ui/` adapts HTTP REST, MCP tools (streamable HTTP, mounted at `/mcp` by `rest`), and websockets to domain usecases. It should parse transport payloads and delegate behavior.
## STRUCTURE
```text
ui/
|-- rest/ # Fiber handlers, helpers, middleware
-|-- mcp/ # MCP tools and default-device context helper
+|-- mcp/ # MCP tools, route mounting, and device resolution
`-- websocket/ # Browser device/status broadcast hub
```
@@ -22,7 +22,7 @@ ui/
| Add REST route | `rest/<domain>.go` | `InitRest*` registers paths and stores the domain service. |
| Add REST middleware | `rest/middleware/` | Use `fiber.Test()` for middleware tests. |
| Add MCP tool | `mcp/<domain>.go` | Define `tool*`, `handle*`, and register in `Add*Tools`. |
-| Device context | `rest/middleware/device.go`, `mcp/helpers/context.go` | REST uses header/query; MCP uses default/only device. |
+| Device context | `rest/middleware/device.go`, `mcp/route.go`, `mcp/device.go` | REST uses header/query; MCP uses the connection's `X-Device-Id` header (set in `route.go`'s `HTTPContextFunc`), overridable per call by a `device_id` tool argument (`resolveDeviceContext`), else the default/only device. |
| Send transport fields | `rest/send.go`, `mcp/send.go` | REST receives full send DTOs; MCP send is a smaller tool subset with manual args. |
| Chatwoot webhook | `rest/chatwoot.go` | Public route, optional shared secret, echo suppression, read/delete sync. |
| Websocket changes | `websocket/websocket.go`, `../views/index.html` | Browser connects with `?device_id=`. |
@@ -35,13 +35,13 @@ ui/
- Chatwoot webhook is registered before basic auth so Chatwoot can POST without the app's Basic Auth header.
- If `CHATWOOT_WEBHOOK_SECRET` is set, the public Chatwoot webhook must pass the shared-secret check before sending to WhatsApp.
- MCP handlers validate argument types manually and return `mcp.NewToolResultText(...)`.
-- MCP handlers must call `ContextWithDefaultDevice` before device-bound usecase calls.
-- MCP coverage is intentionally selective: send has 6 tools, query 5, app 5, and group 13.
+- MCP handlers must resolve the device via `resolveDeviceContext` (`mcp/device.go`) before device-bound usecase calls.
+- MCP exposes 5 consolidated tools: `whatsapp_send`, `whatsapp_message`, `whatsapp_chat`, `whatsapp_group`, `whatsapp_app`; each dispatches on a `type`/`action` argument rather than being one tool per operation.
## ANTI-PATTERNS
- Do not put WhatsApp business logic in REST/MCP handlers.
-- Do not assume MCP receives a device header or device ID argument; use `ContextWithDefaultDevice`.
+- Do not assume every MCP call carries a `device_id` argument; fall through to the connection's `X-Device-Id`-derived device via `resolveDeviceContext`, and only then the default/only device.
- Do not register device-scoped REST operations outside `DeviceMiddleware`.
- Do not expose new unauthenticated REST paths unless they are health checks or explicitly public webhooks.
- Do not remove Chatwoot `source_id` and sent-message cache echo guards without a replacement loop breaker.
diff --git a/src/ui/mcp/app.go b/src/ui/mcp/app.go
index 020dcdcb..00cad572 100644
--- a/src/ui/mcp/app.go
+++ b/src/ui/mcp/app.go
@@ -3,201 +3,98 @@ package mcp
import (
"context"
"encoding/base64"
+ "encoding/json"
"fmt"
"os"
"strings"
domainApp "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/app"
- "github.com/mark3labs/mcp-go/mcp"
+ mcpg "github.com/mark3labs/mcp-go/mcp"
"github.com/mark3labs/mcp-go/server"
)
type AppHandler struct {
appService domainApp.IAppUsecase
+ resolver deviceResolver
}
-func InitMcpApp(appService domainApp.IAppUsecase) *AppHandler {
- return &AppHandler{appService: appService}
+func InitMcpApp(appService domainApp.IAppUsecase, resolver deviceResolver) *AppHandler {
+ return &AppHandler{appService: appService, resolver: resolver}
}
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) {
- deviceID, err := h.defaultDeviceID()
- if err != nil {
- return nil, err
- }
-
- isConnected, isLoggedIn, err := h.appService.Status(context.Background(), deviceID)
- if err != nil {
- return nil, err
- }
-
- structured := map[string]any{
- "is_connected": isConnected,
- "is_logged_in": isLoggedIn,
- "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),
+ tool := mcpg.NewTool("whatsapp_app",
+ mcpg.WithDescription("WhatsApp connection and session management: status, login_qr (returns QR image), login_code (pairing code for a phone number), logout, reconnect."),
+ mcpg.WithTitleAnnotation("Connection & Session"),
+ mcpg.WithReadOnlyHintAnnotation(false),
+ mcpg.WithDestructiveHintAnnotation(true),
+ mcpg.WithIdempotentHintAnnotation(false),
+ mcpg.WithRawInputSchema(json.RawMessage(appSchema)),
)
+ // NewTool defaults InputSchema.Type to "object"; clear it so only
+ // RawInputSchema is set, or MarshalJSON rejects the tool as conflicting.
+ tool.InputSchema = mcpg.ToolInputSchema{}
+ mcpServer.AddTool(tool, h.handleApp)
}
-func (h *AppHandler) handleLoginWithQR(ctx context.Context, _ mcp.CallToolRequest) (*mcp.CallToolResult, error) {
- deviceID, err := h.defaultDeviceID()
+func (h *AppHandler) handleApp(ctx context.Context, request mcpg.CallToolRequest) (*mcpg.CallToolResult, error) {
+ ctx, inst, err := resolveDeviceContext(ctx, request, h.resolver)
if err != nil {
- return nil, err
+ return mcpg.NewToolResultError(err.Error()), nil
}
+ deviceID := inst.ID()
- resp, err := h.appService.Login(ctx, deviceID)
+ action, err := request.RequireString("action")
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{
- "device_id": deviceID,
- "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)
- deviceID, err := h.defaultDeviceID()
- if err != nil {
- return nil, err
- }
-
- pairCode, err := h.appService.LoginWithCode(ctx, deviceID, trimmedPhone)
- if err != nil {
- return nil, err
- }
-
- structured := map[string]any{
- "device_id": deviceID,
- "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) {
- deviceID, err := h.defaultDeviceID()
- if err != nil {
- return nil, err
- }
-
- if err := h.appService.Logout(ctx, deviceID); err != nil {
- return nil, err
- }
-
- return mcp.NewToolResultText(fmt.Sprintf("Logged out device %s successfully", deviceID)), 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) {
- deviceID, err := h.defaultDeviceID()
- if err != nil {
- return nil, err
- }
-
- if err := h.appService.Reconnect(ctx, deviceID); err != nil {
- return nil, err
- }
-
- return mcp.NewToolResultText(fmt.Sprintf("Reconnect initiated for %s", deviceID)), nil
-}
-
-func (h *AppHandler) defaultDeviceID() (string, error) {
- devices, err := h.appService.FetchDevices(context.Background())
- if err != nil {
- return "", err
- }
- if len(devices) == 0 {
- return "", fmt.Errorf("no devices registered")
+ return mcpg.NewToolResultError(err.Error()), nil
+ }
+
+ switch action {
+ case "status":
+ isConnected, isLoggedIn, err := h.appService.Status(ctx, deviceID)
+ if err != nil {
+ return mcpg.NewToolResultError(err.Error()), nil
+ }
+ structured := map[string]any{"is_connected": isConnected, "is_logged_in": isLoggedIn, "device_id": deviceID}
+ return mcpg.NewToolResultStructured(structured, fmt.Sprintf("connected=%t logged_in=%t", isConnected, isLoggedIn)), nil
+ case "login_qr":
+ resp, err := h.appService.Login(ctx, deviceID)
+ if err != nil {
+ return mcpg.NewToolResultError(err.Error()), nil
+ }
+ fallback := fmt.Sprintf("Scan the QR image to log in (expires in ~%d seconds)", int(resp.Duration.Seconds()))
+ structured := map[string]any{
+ "device_id": deviceID,
+ "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 mcpg.NewToolResultStructured(structured, fmt.Sprintf("%s. QR image unavailable: %v", fallback, readErr)), nil
+ }
+ result := mcpg.NewToolResultImage(fallback, base64.StdEncoding.EncodeToString(qrBytes), "image/png")
+ result.StructuredContent = structured
+ return result, nil
+ case "login_code":
+ phone := strings.TrimSpace(request.GetString("phone", ""))
+ pairCode, err := h.appService.LoginWithCode(ctx, deviceID, phone)
+ if err != nil {
+ return mcpg.NewToolResultError(err.Error()), nil
+ }
+ structured := map[string]any{"device_id": deviceID, "phone": phone, "pair_code": pairCode}
+ return mcpg.NewToolResultStructured(structured, fmt.Sprintf("Pair code %s generated for %s", pairCode, phone)), nil
+ case "logout":
+ if err := h.appService.Logout(ctx, deviceID); err != nil {
+ return mcpg.NewToolResultError(err.Error()), nil
+ }
+ return mcpg.NewToolResultText(fmt.Sprintf("Logged out device %s successfully", deviceID)), nil
+ case "reconnect":
+ if err := h.appService.Reconnect(ctx, deviceID); err != nil {
+ return mcpg.NewToolResultError(err.Error()), nil
+ }
+ return mcpg.NewToolResultText(fmt.Sprintf("Reconnect initiated for %s", deviceID)), nil
+ default:
+ return mcpg.NewToolResultError(fmt.Sprintf("unknown app action: %s", action)), nil
}
- return devices[0].Device, nil
}
diff --git a/src/ui/mcp/app_test.go b/src/ui/mcp/app_test.go
new file mode 100644
index 00000000..86ea8809
--- /dev/null
+++ b/src/ui/mcp/app_test.go
@@ -0,0 +1,92 @@
+package mcp
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ domainApp "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/app"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+type stubAppService struct {
+ domainApp.IAppUsecase
+ statusDeviceID string
+ loggedOut string
+ reconnected string
+ loginDeviceID string
+ pairPhone string
+}
+
+func (s *stubAppService) Status(_ context.Context, deviceID string) (bool, bool, error) {
+ s.statusDeviceID = deviceID
+ return true, true, nil
+}
+func (s *stubAppService) Login(_ context.Context, deviceID string) (domainApp.LoginResponse, error) {
+ s.loginDeviceID = deviceID
+ return domainApp.LoginResponse{ImagePath: "/nonexistent/qr.png", Code: "QRDATA", Duration: 30 * time.Second}, nil
+}
+func (s *stubAppService) LoginWithCode(_ context.Context, deviceID string, phone string) (string, error) {
+ s.loginDeviceID = deviceID
+ s.pairPhone = phone
+ return "PAIR-CODE", nil
+}
+func (s *stubAppService) Logout(_ context.Context, deviceID string) error {
+ s.loggedOut = deviceID
+ return nil
+}
+func (s *stubAppService) Reconnect(_ context.Context, deviceID string) error {
+ s.reconnected = deviceID
+ return nil
+}
+
+func TestHandleAppDispatch(t *testing.T) {
+ t.Run("status", func(t *testing.T) {
+ svc := &stubAppService{}
+ h := InitMcpApp(svc, &stubResolver{})
+ res, err := h.handleApp(deviceCtx(), callReq(map[string]any{"action": "status"}))
+ require.NoError(t, err)
+ assert.False(t, res.IsError)
+ })
+
+ t.Run("login_qr survives unreadable image", func(t *testing.T) {
+ svc := &stubAppService{}
+ h := InitMcpApp(svc, &stubResolver{})
+ res, err := h.handleApp(deviceCtx(), callReq(map[string]any{"action": "login_qr"}))
+ require.NoError(t, err)
+ assert.False(t, res.IsError) // falls back to structured result without image
+ })
+
+ t.Run("login_code", func(t *testing.T) {
+ svc := &stubAppService{}
+ h := InitMcpApp(svc, &stubResolver{})
+ _, err := h.handleApp(deviceCtx(), callReq(map[string]any{"action": "login_code", "phone": " +628123 "}))
+ require.NoError(t, err)
+ assert.Equal(t, "+628123", svc.pairPhone)
+ })
+
+ t.Run("logout", func(t *testing.T) {
+ svc := &stubAppService{}
+ h := InitMcpApp(svc, &stubResolver{})
+ res, err := h.handleApp(deviceCtx(), callReq(map[string]any{"action": "logout"}))
+ require.NoError(t, err)
+ assert.False(t, res.IsError)
+ })
+
+ t.Run("reconnect", func(t *testing.T) {
+ svc := &stubAppService{}
+ h := InitMcpApp(svc, &stubResolver{})
+ res, err := h.handleApp(deviceCtx(), callReq(map[string]any{"action": "reconnect"}))
+ require.NoError(t, err)
+ assert.False(t, res.IsError)
+ })
+
+ t.Run("no device is a tool error", func(t *testing.T) {
+ svc := &stubAppService{}
+ h := InitMcpApp(svc, &stubResolver{})
+ res, err := h.handleApp(context.Background(), callReq(map[string]any{"action": "status"}))
+ require.NoError(t, err)
+ assert.True(t, res.IsError)
+ })
+}
diff --git a/src/ui/mcp/chat.go b/src/ui/mcp/chat.go
new file mode 100644
index 00000000..fe61ccbd
--- /dev/null
+++ b/src/ui/mcp/chat.go
@@ -0,0 +1,114 @@
+package mcp
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "strings"
+
+ domainChat "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chat"
+ domainUser "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/user"
+ mcpg "github.com/mark3labs/mcp-go/mcp"
+ "github.com/mark3labs/mcp-go/server"
+)
+
+type ChatHandler struct {
+ chatService domainChat.IChatUsecase
+ userService domainUser.IUserUsecase
+ resolver deviceResolver
+}
+
+func InitMcpChat(chatService domainChat.IChatUsecase, userService domainUser.IUserUsecase, resolver deviceResolver) *ChatHandler {
+ return &ChatHandler{chatService: chatService, userService: userService, resolver: resolver}
+}
+
+func (h *ChatHandler) AddChatTools(mcpServer *server.MCPServer) {
+ tool := mcpg.NewTool("whatsapp_chat",
+ mcpg.WithDescription("Query WhatsApp chats and contacts: list_chats, list_contacts, get_messages (chat history with filters), or archive/unarchive a chat."),
+ mcpg.WithTitleAnnotation("Chat Queries"),
+ mcpg.WithReadOnlyHintAnnotation(false),
+ mcpg.WithDestructiveHintAnnotation(false),
+ mcpg.WithIdempotentHintAnnotation(true),
+ mcpg.WithRawInputSchema(json.RawMessage(chatSchema)),
+ )
+ // NewTool defaults InputSchema.Type to "object"; clear it so only
+ // RawInputSchema is set, or MarshalJSON rejects the tool as conflicting.
+ tool.InputSchema = mcpg.ToolInputSchema{}
+ mcpServer.AddTool(tool, h.handleChat)
+}
+
+func (h *ChatHandler) handleChat(ctx context.Context, request mcpg.CallToolRequest) (*mcpg.CallToolResult, error) {
+ ctx, _, err := resolveDeviceContext(ctx, request, h.resolver)
+ if err != nil {
+ return mcpg.NewToolResultError(err.Error()), nil
+ }
+
+ action, err := request.RequireString("action")
+ if err != nil {
+ return mcpg.NewToolResultError(err.Error()), nil
+ }
+
+ switch action {
+ case "list_chats":
+ req := domainChat.ListChatsRequest{
+ Limit: request.GetInt("limit", 25),
+ Offset: request.GetInt("offset", 0),
+ Search: request.GetString("search", ""),
+ HasMedia: request.GetBool("has_media", false),
+ }
+ resp, err := h.chatService.ListChats(ctx, req)
+ if err != nil {
+ return mcpg.NewToolResultError(err.Error()), nil
+ }
+ return mcpg.NewToolResultStructured(resp, fmt.Sprintf("Retrieved %d chats (offset %d, limit %d)", len(resp.Data), req.Offset, req.Limit)), nil
+ case "list_contacts":
+ resp, err := h.userService.MyListContacts(ctx)
+ if err != nil {
+ return mcpg.NewToolResultError(err.Error()), nil
+ }
+ return mcpg.NewToolResultStructured(resp, fmt.Sprintf("Found %d contacts", len(resp.Data))), nil
+ case "get_messages":
+ chatJID := request.GetString("chat_jid", "")
+ var startTimePtr, endTimePtr *string
+ if v := strings.TrimSpace(request.GetString("start_time", "")); v != "" {
+ startTimePtr = &v
+ }
+ if v := strings.TrimSpace(request.GetString("end_time", "")); v != "" {
+ endTimePtr = &v
+ }
+ var isFromMePtr *bool
+ if args := request.GetArguments(); args != nil {
+ if _, ok := args["is_from_me"]; ok {
+ v := request.GetBool("is_from_me", false)
+ isFromMePtr = &v
+ }
+ }
+ req := domainChat.GetChatMessagesRequest{
+ ChatJID: chatJID,
+ Limit: request.GetInt("limit", 50),
+ Offset: request.GetInt("offset", 0),
+ StartTime: startTimePtr,
+ EndTime: endTimePtr,
+ MediaOnly: request.GetBool("media_only", false),
+ IsFromMe: isFromMePtr,
+ Search: request.GetString("search", ""),
+ }
+ resp, err := h.chatService.GetChatMessages(ctx, req)
+ if err != nil {
+ return mcpg.NewToolResultError(err.Error()), nil
+ }
+ return mcpg.NewToolResultStructured(resp, fmt.Sprintf("Retrieved %d messages from %s", len(resp.Data), chatJID)), nil
+ case "archive":
+ req := domainChat.ArchiveChatRequest{
+ ChatJID: request.GetString("chat_jid", ""),
+ Archived: request.GetBool("archived", false),
+ }
+ resp, err := h.chatService.ArchiveChat(ctx, req)
+ if err != nil {
+ return mcpg.NewToolResultError(err.Error()), nil
+ }
+ return mcpg.NewToolResultStructured(resp, resp.Message), nil
+ default:
+ return mcpg.NewToolResultError(fmt.Sprintf("unknown chat action: %s", action)), nil
+ }
+}
diff --git a/src/ui/mcp/chat_test.go b/src/ui/mcp/chat_test.go
new file mode 100644
index 00000000..e26ddb0f
--- /dev/null
+++ b/src/ui/mcp/chat_test.go
@@ -0,0 +1,91 @@
+package mcp
+
+import (
+ "context"
+ "testing"
+
+ domainChat "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chat"
+ domainUser "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/user"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+type stubChatService struct {
+ domainChat.IChatUsecase
+ listed *domainChat.ListChatsRequest
+ fetched *domainChat.GetChatMessagesRequest
+ archived *domainChat.ArchiveChatRequest
+}
+
+func (s *stubChatService) ListChats(_ context.Context, r domainChat.ListChatsRequest) (domainChat.ListChatsResponse, error) {
+ s.listed = &r
+ return domainChat.ListChatsResponse{}, nil
+}
+func (s *stubChatService) GetChatMessages(_ context.Context, r domainChat.GetChatMessagesRequest) (domainChat.GetChatMessagesResponse, error) {
+ s.fetched = &r
+ return domainChat.GetChatMessagesResponse{}, nil
+}
+func (s *stubChatService) ArchiveChat(_ context.Context, r domainChat.ArchiveChatRequest) (domainChat.ArchiveChatResponse, error) {
+ s.archived = &r
+ return domainChat.ArchiveChatResponse{}, nil
+}
+
+type stubUserService struct {
+ domainUser.IUserUsecase
+ contactsCalled bool
+}
+
+func (s *stubUserService) MyListContacts(_ context.Context) (domainUser.MyListContactsResponse, error) {
+ s.contactsCalled = true
+ return domainUser.MyListContactsResponse{}, nil
+}
+
+func TestHandleChatDispatch(t *testing.T) {
+ t.Run("list_chats with filters", func(t *testing.T) {
+ cs, us := &stubChatService{}, &stubUserService{}
+ h := InitMcpChat(cs, us, &stubResolver{})
+ _, err := h.handleChat(deviceCtx(), callReq(map[string]any{
+ "action": "list_chats", "limit": 10, "search": "bob", "has_media": true,
+ }))
+ require.NoError(t, err)
+ require.NotNil(t, cs.listed)
+ assert.Equal(t, 10, cs.listed.Limit)
+ assert.Equal(t, "bob", cs.listed.Search)
+ assert.True(t, cs.listed.HasMedia)
+ })
+
+ t.Run("list_contacts", func(t *testing.T) {
+ cs, us := &stubChatService{}, &stubUserService{}
+ h := InitMcpChat(cs, us, &stubResolver{})
+ _, err := h.handleChat(deviceCtx(), callReq(map[string]any{"action": "list_contacts"}))
+ require.NoError(t, err)
+ assert.True(t, us.contactsCalled)
+ })
+
+ t.Run("get_messages with time filters", func(t *testing.T) {
+ cs, us := &stubChatService{}, &stubUserService{}
+ h := InitMcpChat(cs, us, &stubResolver{})
+ _, err := h.handleChat(deviceCtx(), callReq(map[string]any{
+ "action": "get_messages", "chat_jid": "[email protected]",
+ "start_time": "2026-01-01T00:00:00Z", "is_from_me": true,
+ }))
+ require.NoError(t, err)
+ require.NotNil(t, cs.fetched)
+ assert.Equal(t, "[email protected]", cs.fetched.ChatJID)
+ require.NotNil(t, cs.fetched.StartTime)
+ assert.Equal(t, "2026-01-01T00:00:00Z", *cs.fetched.StartTime)
+ require.NotNil(t, cs.fetched.IsFromMe)
+ assert.True(t, *cs.fetched.IsFromMe)
+ })
+
+ t.Run("archive", func(t *testing.T) {
+ cs, us := &stubChatService{}, &stubUserService{}
+ h := InitMcpChat(cs, us, &stubResolver{})
+ _, err := h.handleChat(deviceCtx(), callReq(map[string]any{
+ "action": "archive", "chat_jid": "[email protected]", "archived": true,
+ }))
+ require.NoError(t, err)
+ require.NotNil(t, cs.archived)
+ assert.True(t, cs.archived.Archived)
+ })
+}
diff --git a/src/ui/mcp/device.go b/src/ui/mcp/device.go
new file mode 100644
index 00000000..7e98e29e
--- /dev/null
+++ b/src/ui/mcp/device.go
@@ -0,0 +1,36 @@
+package mcp
+
+import (
+ "context"
+ "errors"
+ "strings"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"
+ mcpg "github.com/mark3labs/mcp-go/mcp"
+)
+
+// deviceResolver is the subset of *whatsapp.DeviceManager the MCP layer needs.
+type deviceResolver interface {
+ ResolveDevice(deviceID string) (*whatsapp.DeviceInstance, string, error)
+}
+
+// resolveDeviceContext returns a context carrying the device a tool call acts
+// on. Priority: explicit device_id argument > device injected by the HTTP
+// layer from the X-Device-Id header (see route.go) > error. Mirrors REST's
+// DeviceMiddleware semantics for MCP handlers.
+func resolveDeviceContext(ctx context.Context, request mcpg.CallToolRequest, resolver deviceResolver) (context.Context, *whatsapp.DeviceInstance, error) {
+ if deviceID := strings.TrimSpace(request.GetString("device_id", "")); deviceID != "" {
+ if resolver == nil {
+ return ctx, nil, errors.New("device manager not initialized")
+ }
+ inst, _, err := resolver.ResolveDevice(deviceID)
+ if err != nil {
+ return ctx, nil, err
+ }
+ return whatsapp.ContextWithDevice(ctx, inst), inst, nil
+ }
+ if inst, ok := whatsapp.DeviceFromContext(ctx); ok && inst != nil {
+ return ctx, inst, nil
+ }
+ return ctx, nil, errors.New("device identification required: set the X-Device-Id header or pass device_id")
+}
diff --git a/src/ui/mcp/device_test.go b/src/ui/mcp/device_test.go
new file mode 100644
index 00000000..87479d33
--- /dev/null
+++ b/src/ui/mcp/device_test.go
@@ -0,0 +1,70 @@
+package mcp
+
+import (
+ "context"
+ "errors"
+ "testing"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"
+ mcpg "github.com/mark3labs/mcp-go/mcp"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+type stubResolver struct {
+ inst *whatsapp.DeviceInstance
+ gotID string
+ err error
+}
+
+func (s *stubResolver) ResolveDevice(deviceID string) (*whatsapp.DeviceInstance, string, error) {
+ s.gotID = deviceID
+ return s.inst, deviceID, s.err
+}
+
+func callReq(args map[string]any) mcpg.CallToolRequest {
+ req := mcpg.CallToolRequest{}
+ req.Params.Arguments = args
+ return req
+}
+
+func TestResolveDeviceContext(t *testing.T) {
+ ctxDevice := &whatsapp.DeviceInstance{}
+ argDevice := &whatsapp.DeviceInstance{}
+
+ t.Run("device_id arg overrides context device", func(t *testing.T) {
+ r := &stubResolver{inst: argDevice}
+ ctx := whatsapp.ContextWithDevice(context.Background(), ctxDevice)
+ newCtx, inst, err := resolveDeviceContext(ctx, callReq(map[string]any{"device_id": "dev2"}), r)
+ require.NoError(t, err)
+ assert.Same(t, argDevice, inst)
+ assert.Equal(t, "dev2", r.gotID)
+ got, ok := whatsapp.DeviceFromContext(newCtx)
+ require.True(t, ok)
+ assert.Same(t, argDevice, got)
+ })
+
+ t.Run("falls back to context device", func(t *testing.T) {
+ ctx := whatsapp.ContextWithDevice(context.Background(), ctxDevice)
+ _, inst, err := resolveDeviceContext(ctx, callReq(nil), &stubResolver{})
+ require.NoError(t, err)
+ assert.Same(t, ctxDevice, inst)
+ })
+
+ t.Run("resolver error surfaces", func(t *testing.T) {
+ r := &stubResolver{err: errors.New("no such device")}
+ _, _, err := resolveDeviceContext(context.Background(), callReq(map[string]any{"device_id": "ghost"}), r)
+ require.ErrorContains(t, err, "no such device")
+ })
+
+ t.Run("no device anywhere errors", func(t *testing.T) {
+ _, _, err := resolveDeviceContext(context.Background(), callReq(nil), &stubResolver{})
+ require.ErrorContains(t, err, "device identification required")
+ })
+
+ t.Run("nil device stored in context errors", func(t *testing.T) {
+ ctx := whatsapp.ContextWithDevice(context.Background(), nil)
+ _, _, err := resolveDeviceContext(ctx, callReq(nil), &stubResolver{})
+ require.ErrorContains(t, err, "device identification required")
+ })
+}
diff --git a/src/ui/mcp/group.go b/src/ui/mcp/group.go
index 65ee4517..2ca6c86a 100644
--- a/src/ui/mcp/group.go
+++ b/src/ui/mcp/group.go
@@ -2,741 +2,169 @@ package mcp
import (
"context"
+ "encoding/json"
"fmt"
"strings"
domainGroup "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/group"
"github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
- mcpHelpers "github.com/aldinokemal/go-whatsapp-web-multidevice/ui/mcp/helpers"
- "github.com/mark3labs/mcp-go/mcp"
+ mcpg "github.com/mark3labs/mcp-go/mcp"
"github.com/mark3labs/mcp-go/server"
"go.mau.fi/whatsmeow"
)
type GroupHandler struct {
groupService domainGroup.IGroupUsecase
+ resolver deviceResolver
}
-func InitMcpGroup(groupService domainGroup.IGroupUsecase) *GroupHandler {
- return &GroupHandler{groupService: groupService}
+func InitMcpGroup(groupService domainGroup.IGroupUsecase, resolver deviceResolver) *GroupHandler {
+ return &GroupHandler{groupService: groupService, resolver: resolver}
}
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(),
- ),
+ tool := mcpg.NewTool("whatsapp_group",
+ mcpg.WithDescription("Manage WhatsApp groups: create, join_with_link, leave, info, participants, add/remove/promote/demote participants, invite_link, set_name, set_topic, set_settings (announce/locked), join_requests, manage_join_requests."),
+ mcpg.WithTitleAnnotation("Group Management"),
+ mcpg.WithReadOnlyHintAnnotation(false),
+ mcpg.WithDestructiveHintAnnotation(true),
+ mcpg.WithIdempotentHintAnnotation(false),
+ mcpg.WithRawInputSchema(json.RawMessage(groupSchema)),
)
+ // NewTool defaults InputSchema.Type to "object"; clear it so only
+ // RawInputSchema is set, or MarshalJSON rejects the tool as conflicting.
+ tool.InputSchema = mcpg.ToolInputSchema{}
+ mcpServer.AddTool(tool, h.handleGroup)
}
-func (h *GroupHandler) handleCreateGroup(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
- ctx, err := mcpHelpers.ContextWithDefaultDevice(ctx)
+func (h *GroupHandler) handleGroup(ctx context.Context, request mcpg.CallToolRequest) (*mcpg.CallToolResult, error) {
+ ctx, _, err := resolveDeviceContext(ctx, request, h.resolver)
if err != nil {
- return nil, err
+ return mcpg.NewToolResultError(err.Error()), nil
}
- title, err := request.RequireString("title")
+ action, err := request.RequireString("action")
if err != nil {
- return nil, err
+ return mcpg.NewToolResultError(err.Error()), nil
}
- 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 := strings.TrimSpace(request.GetString("group_id", ""))
+ utils.SanitizePhone(&groupID)
+ participants := trimAll(request.GetStringSlice("participants", nil))
+
+ switch action {
+ case "create":
+ title := strings.TrimSpace(request.GetString("title", ""))
+ newGroupID, err := h.groupService.CreateGroup(ctx, domainGroup.CreateGroupRequest{
+ Title: title, Participants: participants,
+ })
+ if err != nil {
+ return mcpg.NewToolResultError(err.Error()), nil
+ }
+ structured := map[string]any{"group_id": newGroupID, "title": title, "members": len(participants)}
+ return mcpg.NewToolResultStructured(structured, fmt.Sprintf("Created group %s with %d members", newGroupID, len(participants))), nil
+ case "join_with_link":
+ link := strings.TrimSpace(request.GetString("invite_link", ""))
+ joinedID, err := h.groupService.JoinGroupWithLink(ctx, domainGroup.JoinGroupWithLinkRequest{Link: link})
+ if err != nil {
+ return mcpg.NewToolResultError(err.Error()), nil
+ }
+ structured := map[string]any{"group_id": joinedID, "invite_link": link}
+ return mcpg.NewToolResultStructured(structured, fmt.Sprintf("Joined group %s", joinedID)), nil
+ case "leave":
+ if err := h.groupService.LeaveGroup(ctx, domainGroup.LeaveGroupRequest{GroupID: groupID}); err != nil {
+ return mcpg.NewToolResultError(err.Error()), nil
+ }
+ return mcpg.NewToolResultText(fmt.Sprintf("Left group %s", groupID)), nil
+ case "info":
+ resp, err := h.groupService.GroupInfo(ctx, domainGroup.GroupInfoRequest{GroupID: groupID})
+ if err != nil {
+ return mcpg.NewToolResultError(err.Error()), nil
+ }
+ return mcpg.NewToolResultStructured(resp, fmt.Sprintf("Fetched group info for %s", groupID)), nil
+ case "participants":
+ resp, err := h.groupService.GetGroupParticipants(ctx, domainGroup.GetGroupParticipantsRequest{GroupID: groupID})
+ if err != nil {
+ return mcpg.NewToolResultError(err.Error()), nil
+ }
+ return mcpg.NewToolResultStructured(resp, fmt.Sprintf("Group %s has %d participants", resp.GroupID, len(resp.Participants))), nil
+ case "add_participants", "remove_participants", "promote", "demote":
+ change := map[string]whatsmeow.ParticipantChange{
+ "add_participants": whatsmeow.ParticipantChangeAdd,
+ "remove_participants": whatsmeow.ParticipantChangeRemove,
+ "promote": whatsmeow.ParticipantChangePromote,
+ "demote": whatsmeow.ParticipantChangeDemote,
+ }[action]
+ result, err := h.groupService.ManageParticipant(ctx, domainGroup.ParticipantRequest{
+ GroupID: groupID, Participants: participants, Action: change,
+ })
+ if err != nil {
+ return mcpg.NewToolResultError(err.Error()), nil
+ }
+ return mcpg.NewToolResultStructured(result, fmt.Sprintf("Applied %s to %d participants in %s", action, len(participants), groupID)), nil
+ case "invite_link":
+ resp, err := h.groupService.GetGroupInviteLink(ctx, domainGroup.GetGroupInviteLinkRequest{
+ GroupID: groupID, Reset: request.GetBool("reset", false),
+ })
+ if err != nil {
+ return mcpg.NewToolResultError(err.Error()), nil
+ }
+ return mcpg.NewToolResultStructured(resp, fmt.Sprintf("Invite link for %s: %s", groupID, resp.InviteLink)), nil
+ case "set_name":
+ name := strings.TrimSpace(request.GetString("name", ""))
+ if err := h.groupService.SetGroupName(ctx, domainGroup.SetGroupNameRequest{GroupID: groupID, Name: name}); err != nil {
+ return mcpg.NewToolResultError(err.Error()), nil
+ }
+ return mcpg.NewToolResultText(fmt.Sprintf("Updated group %s name to %s", groupID, name)), nil
+ case "set_topic":
+ topic := strings.TrimSpace(request.GetString("topic", ""))
+ if err := h.groupService.SetGroupTopic(ctx, domainGroup.SetGroupTopicRequest{GroupID: groupID, Topic: topic}); err != nil {
+ return mcpg.NewToolResultError(err.Error()), nil
+ }
+ return mcpg.NewToolResultText(fmt.Sprintf("Updated group %s topic", groupID)), nil
+ case "set_settings":
+ args := request.GetArguments()
+ applied := []string{}
+ if _, ok := args["announce"]; ok {
+ if err := h.groupService.SetGroupAnnounce(ctx, domainGroup.SetGroupAnnounceRequest{
+ GroupID: groupID, Announce: request.GetBool("announce", false),
+ }); err != nil {
+ return mcpg.NewToolResultError(err.Error()), nil
}
+ applied = append(applied, "announce")
}
- }
-
- 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) {
- ctx, err := mcpHelpers.ContextWithDefaultDevice(ctx)
- if err != nil {
- return nil, err
- }
-
- 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) {
- ctx, err := mcpHelpers.ContextWithDefaultDevice(ctx)
- if err != nil {
- return nil, err
- }
-
- 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) {
- ctx, err := mcpHelpers.ContextWithDefaultDevice(ctx)
- if err != nil {
- return nil, err
- }
-
- 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) {
- ctx, err := mcpHelpers.ContextWithDefaultDevice(ctx)
- if err != nil {
- return nil, err
- }
-
- 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) {
- ctx, err := mcpHelpers.ContextWithDefaultDevice(ctx)
- if err != nil {
- return nil, err
- }
-
- 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
+ if _, ok := args["locked"]; ok {
+ if err := h.groupService.SetGroupLocked(ctx, domainGroup.SetGroupLockedRequest{
+ GroupID: groupID, Locked: request.GetBool("locked", false),
+ }); err != nil {
+ return mcpg.NewToolResultError(err.Error()), nil
}
- reset = parsed
+ applied = append(applied, "locked")
}
- }
-
- 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) {
- ctx, err := mcpHelpers.ContextWithDefaultDevice(ctx)
- if err != nil {
- return nil, err
- }
-
- 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) {
- ctx, err := mcpHelpers.ContextWithDefaultDevice(ctx)
- if err != nil {
- return nil, err
- }
-
- 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) {
- ctx, err := mcpHelpers.ContextWithDefaultDevice(ctx)
- if err != nil {
- return nil, err
- }
-
- 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) {
- ctx, err := mcpHelpers.ContextWithDefaultDevice(ctx)
- if err != nil {
- return nil, err
- }
-
- 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) {
- ctx, err := mcpHelpers.ContextWithDefaultDevice(ctx)
- if err != nil {
- return nil, err
- }
-
- 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) {
- ctx, err := mcpHelpers.ContextWithDefaultDevice(ctx)
- if err != nil {
- return nil, err
- }
-
- 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) {
- ctx, err := mcpHelpers.ContextWithDefaultDevice(ctx)
- if err != nil {
- return nil, err
- }
-
- 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
+ if len(applied) == 0 {
+ return mcpg.NewToolResultError("set_settings requires announce and/or locked"), nil
+ }
+ return mcpg.NewToolResultText(fmt.Sprintf("Updated %s for group %s", strings.Join(applied, "+"), groupID)), nil
+ case "join_requests":
+ resp, err := h.groupService.GetGroupRequestParticipants(ctx, domainGroup.GetGroupRequestParticipantsRequest{GroupID: groupID})
+ if err != nil {
+ return mcpg.NewToolResultError(err.Error()), nil
+ }
+ return mcpg.NewToolResultStructured(resp, fmt.Sprintf("Group %s has %d pending requests", groupID, len(resp))), nil
+ case "manage_join_requests":
+ change, err := parseParticipantRequestChange(request.GetString("request_action", ""))
+ if err != nil {
+ return mcpg.NewToolResultError(err.Error()), nil
+ }
+ result, err := h.groupService.ManageGroupRequestParticipants(ctx, domainGroup.GroupRequestParticipantsRequest{
+ GroupID: groupID, Participants: participants, Action: change,
+ })
+ if err != nil {
+ return mcpg.NewToolResultError(err.Error()), nil
+ }
+ return mcpg.NewToolResultStructured(result, fmt.Sprintf("Applied %s to %d pending requests for %s", request.GetString("request_action", ""), len(participants), groupID)), nil
default:
- return whatsmeow.ParticipantChange(""), fmt.Errorf("invalid participant action: %s", action)
+ return mcpg.NewToolResultError(fmt.Sprintf("unknown group action: %s", action)), nil
}
}
@@ -751,29 +179,10 @@ func parseParticipantRequestChange(action string) (whatsmeow.ParticipantRequestC
}
}
-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")
+func trimAll(items []string) []string {
+ out := make([]string, len(items))
+ for i, item := range items {
+ out[i] = strings.TrimSpace(item)
}
+ return out
}
diff --git a/src/ui/mcp/group_test.go b/src/ui/mcp/group_test.go
new file mode 100644
index 00000000..4147b864
--- /dev/null
+++ b/src/ui/mcp/group_test.go
@@ -0,0 +1,215 @@
+package mcp
+
+import (
+ "context"
+ "testing"
+
+ domainGroup "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/group"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+ "go.mau.fi/whatsmeow"
+)
+
+type stubGroupService struct {
+ domainGroup.IGroupUsecase
+ created *domainGroup.CreateGroupRequest
+ joined *domainGroup.JoinGroupWithLinkRequest
+ left *domainGroup.LeaveGroupRequest
+ infoReq *domainGroup.GroupInfoRequest
+ partsReq *domainGroup.GetGroupParticipantsRequest
+ managed *domainGroup.ParticipantRequest
+ inviteReq *domainGroup.GetGroupInviteLinkRequest
+ namedReq *domainGroup.SetGroupNameRequest
+ topicReq *domainGroup.SetGroupTopicRequest
+ announceReq *domainGroup.SetGroupAnnounceRequest
+ lockedReq *domainGroup.SetGroupLockedRequest
+ joinReqsReq *domainGroup.GetGroupRequestParticipantsRequest
+ managedJoins *domainGroup.GroupRequestParticipantsRequest
+}
+
+func (s *stubGroupService) CreateGroup(_ context.Context, r domainGroup.CreateGroupRequest) (string, error) {
+ s.created = &r
+ return "[email protected]", nil
+}
+func (s *stubGroupService) JoinGroupWithLink(_ context.Context, r domainGroup.JoinGroupWithLinkRequest) (string, error) {
+ s.joined = &r
+ return "[email protected]", nil
+}
+func (s *stubGroupService) LeaveGroup(_ context.Context, r domainGroup.LeaveGroupRequest) error {
+ s.left = &r
+ return nil
+}
+func (s *stubGroupService) GroupInfo(_ context.Context, r domainGroup.GroupInfoRequest) (domainGroup.GroupInfoResponse, error) {
+ s.infoReq = &r
+ return domainGroup.GroupInfoResponse{}, nil
+}
+func (s *stubGroupService) GetGroupParticipants(_ context.Context, r domainGroup.GetGroupParticipantsRequest) (domainGroup.GetGroupParticipantsResponse, error) {
+ s.partsReq = &r
+ return domainGroup.GetGroupParticipantsResponse{}, nil
+}
+func (s *stubGroupService) ManageParticipant(_ context.Context, r domainGroup.ParticipantRequest) ([]domainGroup.ParticipantStatus, error) {
+ s.managed = &r
+ return nil, nil
+}
+func (s *stubGroupService) GetGroupInviteLink(_ context.Context, r domainGroup.GetGroupInviteLinkRequest) (domainGroup.GetGroupInviteLinkResponse, error) {
+ s.inviteReq = &r
+ return domainGroup.GetGroupInviteLinkResponse{InviteLink: "http://x"}, nil
+}
+func (s *stubGroupService) SetGroupName(_ context.Context, r domainGroup.SetGroupNameRequest) error {
+ s.namedReq = &r
+ return nil
+}
+func (s *stubGroupService) SetGroupTopic(_ context.Context, r domainGroup.SetGroupTopicRequest) error {
+ s.topicReq = &r
+ return nil
+}
+func (s *stubGroupService) SetGroupAnnounce(_ context.Context, r domainGroup.SetGroupAnnounceRequest) error {
+ s.announceReq = &r
+ return nil
+}
+func (s *stubGroupService) SetGroupLocked(_ context.Context, r domainGroup.SetGroupLockedRequest) error {
+ s.lockedReq = &r
+ return nil
+}
+func (s *stubGroupService) GetGroupRequestParticipants(_ context.Context, r domainGroup.GetGroupRequestParticipantsRequest) ([]domainGroup.GetGroupRequestParticipantsResponse, error) {
+ s.joinReqsReq = &r
+ return nil, nil
+}
+func (s *stubGroupService) ManageGroupRequestParticipants(_ context.Context, r domainGroup.GroupRequestParticipantsRequest) ([]domainGroup.ParticipantStatus, error) {
+ s.managedJoins = &r
+ return nil, nil
+}
+
+func TestHandleGroupDispatch(t *testing.T) {
+ newHandler := func() (*stubGroupService, *GroupHandler) {
+ svc := &stubGroupService{}
+ return svc, InitMcpGroup(svc, &stubResolver{})
+ }
+
+ t.Run("create", func(t *testing.T) {
+ svc, h := newHandler()
+ _, err := h.handleGroup(deviceCtx(), callReq(map[string]any{
+ "action": "create", "title": " T ", "participants": []any{"628"},
+ }))
+ require.NoError(t, err)
+ require.NotNil(t, svc.created)
+ assert.Equal(t, "T", svc.created.Title)
+ assert.Equal(t, []string{"628"}, svc.created.Participants)
+ })
+
+ t.Run("join_with_link", func(t *testing.T) {
+ svc, h := newHandler()
+ _, err := h.handleGroup(deviceCtx(), callReq(map[string]any{
+ "action": "join_with_link", "invite_link": "http://chat.whatsapp.com/x",
+ }))
+ require.NoError(t, err)
+ require.NotNil(t, svc.joined)
+ })
+
+ t.Run("leave", func(t *testing.T) {
+ svc, h := newHandler()
+ _, err := h.handleGroup(deviceCtx(), callReq(map[string]any{"action": "leave", "group_id": "[email protected]"}))
+ require.NoError(t, err)
+ require.NotNil(t, svc.left)
+ })
+
+ t.Run("info", func(t *testing.T) {
+ svc, h := newHandler()
+ _, err := h.handleGroup(deviceCtx(), callReq(map[string]any{"action": "info", "group_id": "[email protected]"}))
+ require.NoError(t, err)
+ require.NotNil(t, svc.infoReq)
+ })
+
+ t.Run("participants", func(t *testing.T) {
+ svc, h := newHandler()
+ _, err := h.handleGroup(deviceCtx(), callReq(map[string]any{"action": "participants", "group_id": "[email protected]"}))
+ require.NoError(t, err)
+ require.NotNil(t, svc.partsReq)
+ })
+
+ t.Run("participant changes map to whatsmeow actions", func(t *testing.T) {
+ cases := map[string]whatsmeow.ParticipantChange{
+ "add_participants": whatsmeow.ParticipantChangeAdd,
+ "remove_participants": whatsmeow.ParticipantChangeRemove,
+ "promote": whatsmeow.ParticipantChangePromote,
+ "demote": whatsmeow.ParticipantChangeDemote,
+ }
+ for action, want := range cases {
+ svc, h := newHandler()
+ _, err := h.handleGroup(deviceCtx(), callReq(map[string]any{
+ "action": action, "group_id": "[email protected]", "participants": []any{"628"},
+ }))
+ require.NoError(t, err, action)
+ require.NotNil(t, svc.managed, action)
+ assert.Equal(t, want, svc.managed.Action, action)
+ }
+ })
+
+ t.Run("invite_link with reset", func(t *testing.T) {
+ svc, h := newHandler()
+ _, err := h.handleGroup(deviceCtx(), callReq(map[string]any{
+ "action": "invite_link", "group_id": "[email protected]", "reset": true,
+ }))
+ require.NoError(t, err)
+ require.NotNil(t, svc.inviteReq)
+ assert.True(t, svc.inviteReq.Reset)
+ })
+
+ t.Run("set_name", func(t *testing.T) {
+ svc, h := newHandler()
+ _, err := h.handleGroup(deviceCtx(), callReq(map[string]any{
+ "action": "set_name", "group_id": "[email protected]", "name": "N",
+ }))
+ require.NoError(t, err)
+ require.NotNil(t, svc.namedReq)
+ })
+
+ t.Run("set_topic", func(t *testing.T) {
+ svc, h := newHandler()
+ _, err := h.handleGroup(deviceCtx(), callReq(map[string]any{
+ "action": "set_topic", "group_id": "[email protected]", "topic": "T",
+ }))
+ require.NoError(t, err)
+ require.NotNil(t, svc.topicReq)
+ })
+
+ t.Run("set_settings applies both flags", func(t *testing.T) {
+ svc, h := newHandler()
+ _, err := h.handleGroup(deviceCtx(), callReq(map[string]any{
+ "action": "set_settings", "group_id": "[email protected]", "announce": true, "locked": false,
+ }))
+ require.NoError(t, err)
+ require.NotNil(t, svc.announceReq)
+ assert.True(t, svc.announceReq.Announce)
+ require.NotNil(t, svc.lockedReq)
+ assert.False(t, svc.lockedReq.Locked)
+ })
+
+ t.Run("set_settings announce only", func(t *testing.T) {
+ svc, h := newHandler()
+ _, err := h.handleGroup(deviceCtx(), callReq(map[string]any{
+ "action": "set_settings", "group_id": "[email protected]", "announce": true,
+ }))
+ require.NoError(t, err)
+ require.NotNil(t, svc.announceReq)
+ assert.Nil(t, svc.lockedReq)
+ })
+
+ t.Run("join_requests", func(t *testing.T) {
+ svc, h := newHandler()
+ _, err := h.handleGroup(deviceCtx(), callReq(map[string]any{"action": "join_requests", "group_id": "[email protected]"}))
+ require.NoError(t, err)
+ require.NotNil(t, svc.joinReqsReq)
+ })
+
+ t.Run("manage_join_requests", func(t *testing.T) {
+ svc, h := newHandler()
+ _, err := h.handleGroup(deviceCtx(), callReq(map[string]any{
+ "action": "manage_join_requests", "group_id": "[email protected]",
+ "participants": []any{"628"}, "request_action": "approve",
+ }))
+ require.NoError(t, err)
+ require.NotNil(t, svc.managedJoins)
+ assert.Equal(t, whatsmeow.ParticipantChangeApprove, svc.managedJoins.Action)
+ })
+}
diff --git a/src/ui/mcp/helpers/context.go b/src/ui/mcp/helpers/context.go
deleted file mode 100644
index 22f2c9e2..00000000
--- a/src/ui/mcp/helpers/context.go
+++ /dev/null
@@ -1,25 +0,0 @@
-package helpers
-
-import (
- "context"
- "fmt"
-
- "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"
-)
-
-// ContextWithDefaultDevice resolves the default device from the global DeviceManager
-// and injects it into the provided context. This mirrors what the REST middleware does
-// via Fiber locals, but for MCP handlers which lack HTTP middleware.
-func ContextWithDefaultDevice(ctx context.Context) (context.Context, error) {
- mgr := whatsapp.GetDeviceManager()
- if mgr == nil {
- return ctx, fmt.Errorf("device manager not initialized")
- }
-
- inst, _, err := mgr.ResolveDevice("")
- if err != nil {
- return ctx, fmt.Errorf("device identification required: %w", err)
- }
-
- return whatsapp.ContextWithDevice(ctx, inst), nil
-}
diff --git a/src/ui/mcp/message.go b/src/ui/mcp/message.go
new file mode 100644
index 00000000..eba6390a
--- /dev/null
+++ b/src/ui/mcp/message.go
@@ -0,0 +1,109 @@
+package mcp
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+
+ domainMessage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/message"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
+ mcpg "github.com/mark3labs/mcp-go/mcp"
+ "github.com/mark3labs/mcp-go/server"
+)
+
+type MessageHandler struct {
+ messageService domainMessage.IMessageUsecase
+ resolver deviceResolver
+}
+
+func InitMcpMessage(messageService domainMessage.IMessageUsecase, resolver deviceResolver) *MessageHandler {
+ return &MessageHandler{messageService: messageService, resolver: resolver}
+}
+
+func (h *MessageHandler) AddMessageTools(mcpServer *server.MCPServer) {
+ tool := mcpg.NewTool("whatsapp_message",
+ mcpg.WithDescription("Operate on an existing WhatsApp message: react, edit, revoke (delete for everyone), delete (for me), mark_read, star, unstar, or download_media."),
+ mcpg.WithTitleAnnotation("Message Operations"),
+ mcpg.WithReadOnlyHintAnnotation(false),
+ mcpg.WithDestructiveHintAnnotation(true),
+ mcpg.WithIdempotentHintAnnotation(false),
+ mcpg.WithRawInputSchema(json.RawMessage(messageSchema)),
+ )
+ // NewTool defaults InputSchema.Type to "object"; clear it so only
+ // RawInputSchema is set, or MarshalJSON rejects the tool as conflicting.
+ tool.InputSchema = mcpg.ToolInputSchema{}
+ mcpServer.AddTool(tool, h.handleMessage)
+}
+
+func (h *MessageHandler) handleMessage(ctx context.Context, request mcpg.CallToolRequest) (*mcpg.CallToolResult, error) {
+ ctx, _, err := resolveDeviceContext(ctx, request, h.resolver)
+ if err != nil {
+ return mcpg.NewToolResultError(err.Error()), nil
+ }
+
+ action, err := request.RequireString("action")
+ if err != nil {
+ return mcpg.NewToolResultError(err.Error()), nil
+ }
+ phone, err := request.RequireString("phone")
+ if err != nil {
+ return mcpg.NewToolResultError(err.Error()), nil
+ }
+ utils.SanitizePhone(&phone)
+ messageID, err := request.RequireString("message_id")
+ if err != nil {
+ return mcpg.NewToolResultError(err.Error()), nil
+ }
+
+ switch action {
+ case "react":
+ resp, err := h.messageService.ReactMessage(ctx, domainMessage.ReactionRequest{
+ MessageID: messageID, Phone: phone, Emoji: request.GetString("emoji", ""),
+ })
+ if err != nil {
+ return mcpg.NewToolResultError(err.Error()), nil
+ }
+ return mcpg.NewToolResultStructured(resp, fmt.Sprintf("Reaction sent (message ID: %s)", resp.MessageID)), nil
+ case "edit":
+ resp, err := h.messageService.UpdateMessage(ctx, domainMessage.UpdateMessageRequest{
+ MessageID: messageID, Phone: phone, Message: request.GetString("message", ""),
+ })
+ if err != nil {
+ return mcpg.NewToolResultError(err.Error()), nil
+ }
+ return mcpg.NewToolResultStructured(resp, fmt.Sprintf("Message edited (ID: %s)", resp.MessageID)), nil
+ case "revoke":
+ resp, err := h.messageService.RevokeMessage(ctx, domainMessage.RevokeRequest{MessageID: messageID, Phone: phone})
+ if err != nil {
+ return mcpg.NewToolResultError(err.Error()), nil
+ }
+ return mcpg.NewToolResultStructured(resp, fmt.Sprintf("Message revoked (ID: %s)", resp.MessageID)), nil
+ case "delete":
+ if err := h.messageService.DeleteMessage(ctx, domainMessage.DeleteRequest{MessageID: messageID, Phone: phone}); err != nil {
+ return mcpg.NewToolResultError(err.Error()), nil
+ }
+ return mcpg.NewToolResultText(fmt.Sprintf("Message %s deleted", messageID)), nil
+ case "mark_read":
+ resp, err := h.messageService.MarkAsRead(ctx, domainMessage.MarkAsReadRequest{MessageID: messageID, Phone: phone})
+ if err != nil {
+ return mcpg.NewToolResultError(err.Error()), nil
+ }
+ return mcpg.NewToolResultStructured(resp, fmt.Sprintf("Message marked as read (ID: %s)", resp.MessageID)), nil
+ case "star", "unstar":
+ isStarred := action == "star"
+ if err := h.messageService.StarMessage(ctx, domainMessage.StarRequest{
+ MessageID: messageID, Phone: phone, IsStarred: isStarred,
+ }); err != nil {
+ return mcpg.NewToolResultError(err.Error()), nil
+ }
+ return mcpg.NewToolResultText(fmt.Sprintf("Message %s star=%t", messageID, isStarred)), nil
+ case "download_media":
+ resp, err := h.messageService.DownloadMedia(ctx, domainMessage.DownloadMediaRequest{MessageID: messageID, Phone: phone})
+ if err != nil {
+ return mcpg.NewToolResultError(err.Error()), nil
+ }
+ return mcpg.NewToolResultStructured(resp, fmt.Sprintf("Media saved to %s (%s)", resp.FilePath, resp.MediaType)), nil
+ default:
+ return mcpg.NewToolResultError(fmt.Sprintf("unknown message action: %s", action)), nil
+ }
+}
diff --git a/src/ui/mcp/message_test.go b/src/ui/mcp/message_test.go
new file mode 100644
index 00000000..e976b95d
--- /dev/null
+++ b/src/ui/mcp/message_test.go
@@ -0,0 +1,128 @@
+package mcp
+
+import (
+ "context"
+ "testing"
+
+ domainMessage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/message"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+type stubMessageService struct {
+ domainMessage.IMessageUsecase
+ reacted *domainMessage.ReactionRequest
+ updated *domainMessage.UpdateMessageRequest
+ revoked *domainMessage.RevokeRequest
+ deleted *domainMessage.DeleteRequest
+ marked *domainMessage.MarkAsReadRequest
+ starred *domainMessage.StarRequest
+ downloaded *domainMessage.DownloadMediaRequest
+}
+
+func (s *stubMessageService) ReactMessage(_ context.Context, r domainMessage.ReactionRequest) (domainMessage.GenericResponse, error) {
+ s.reacted = &r
+ return domainMessage.GenericResponse{MessageID: r.MessageID}, nil
+}
+func (s *stubMessageService) UpdateMessage(_ context.Context, r domainMessage.UpdateMessageRequest) (domainMessage.GenericResponse, error) {
+ s.updated = &r
+ return domainMessage.GenericResponse{MessageID: r.MessageID}, nil
+}
+func (s *stubMessageService) RevokeMessage(_ context.Context, r domainMessage.RevokeRequest) (domainMessage.GenericResponse, error) {
+ s.revoked = &r
+ return domainMessage.GenericResponse{MessageID: r.MessageID}, nil
+}
+func (s *stubMessageService) DeleteMessage(_ context.Context, r domainMessage.DeleteRequest) error {
+ s.deleted = &r
+ return nil
+}
+func (s *stubMessageService) MarkAsRead(_ context.Context, r domainMessage.MarkAsReadRequest) (domainMessage.GenericResponse, error) {
+ s.marked = &r
+ return domainMessage.GenericResponse{MessageID: r.MessageID}, nil
+}
+func (s *stubMessageService) StarMessage(_ context.Context, r domainMessage.StarRequest) error {
+ s.starred = &r
+ return nil
+}
+func (s *stubMessageService) DownloadMedia(_ context.Context, r domainMessage.DownloadMediaRequest) (domainMessage.DownloadMediaResponse, error) {
+ s.downloaded = &r
+ return domainMessage.DownloadMediaResponse{FilePath: "/tmp/x.jpg", MediaType: "image"}, nil
+}
+
+func TestHandleMessageDispatch(t *testing.T) {
+ base := map[string]any{"phone": "628", "message_id": "M1"}
+ withAction := func(action string, extra map[string]any) map[string]any {
+ m := map[string]any{"action": action}
+ for k, v := range base {
+ m[k] = v
+ }
+ for k, v := range extra {
+ m[k] = v
+ }
+ return m
+ }
+
+ t.Run("react", func(t *testing.T) {
+ svc := &stubMessageService{}
+ h := InitMcpMessage(svc, &stubResolver{})
+ _, err := h.handleMessage(deviceCtx(), callReq(withAction("react", map[string]any{"emoji": "👍"})))
+ require.NoError(t, err)
+ require.NotNil(t, svc.reacted)
+ assert.Equal(t, "👍", svc.reacted.Emoji)
+ })
+
+ t.Run("edit", func(t *testing.T) {
+ svc := &stubMessageService{}
+ h := InitMcpMessage(svc, &stubResolver{})
+ _, err := h.handleMessage(deviceCtx(), callReq(withAction("edit", map[string]any{"message": "new"})))
+ require.NoError(t, err)
+ require.NotNil(t, svc.updated)
+ assert.Equal(t, "new", svc.updated.Message)
+ })
+
+ t.Run("revoke", func(t *testing.T) {
+ svc := &stubMessageService{}
+ h := InitMcpMessage(svc, &stubResolver{})
+ _, err := h.handleMessage(deviceCtx(), callReq(withAction("revoke", nil)))
+ require.NoError(t, err)
+ require.NotNil(t, svc.revoked)
+ })
+
+ t.Run("delete", func(t *testing.T) {
+ svc := &stubMessageService{}
+ h := InitMcpMessage(svc, &stubResolver{})
+ _, err := h.handleMessage(deviceCtx(), callReq(withAction("delete", nil)))
+ require.NoError(t, err)
+ require.NotNil(t, svc.deleted)
+ })
+
+ t.Run("mark_read", func(t *testing.T) {
+ svc := &stubMessageService{}
+ h := InitMcpMessage(svc, &stubResolver{})
+ _, err := h.handleMessage(deviceCtx(), callReq(withAction("mark_read", nil)))
+ require.NoError(t, err)
+ require.NotNil(t, svc.marked)
+ })
+
+ t.Run("star and unstar", func(t *testing.T) {
+ svc := &stubMessageService{}
+ h := InitMcpMessage(svc, &stubResolver{})
+ _, err := h.handleMessage(deviceCtx(), callReq(withAction("star", nil)))
+ require.NoError(t, err)
+ require.NotNil(t, svc.starred)
+ assert.True(t, svc.starred.IsStarred)
+
+ _, err = h.handleMessage(deviceCtx(), callReq(withAction("unstar", nil)))
+ require.NoError(t, err)
+ assert.False(t, svc.starred.IsStarred)
+ })
+
+ t.Run("download_media", func(t *testing.T) {
+ svc := &stubMessageService{}
+ h := InitMcpMessage(svc, &stubResolver{})
+ res, err := h.handleMessage(deviceCtx(), callReq(withAction("download_media", nil)))
+ require.NoError(t, err)
+ require.NotNil(t, svc.downloaded)
+ assert.False(t, res.IsError)
+ })
+}
diff --git a/src/ui/mcp/query.go b/src/ui/mcp/query.go
deleted file mode 100644
index e0e041c4..00000000
--- a/src/ui/mcp/query.go
+++ /dev/null
@@ -1,692 +0,0 @@
-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"
- mcpHelpers "github.com/aldinokemal/go-whatsapp-web-multidevice/ui/mcp/helpers"
- "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)
- mcpServer.AddTool(h.toolArchiveChat(), h.handleArchiveChat)
- mcpServer.AddTool(h.toolReactMessage(), h.handleReactMessage)
- mcpServer.AddTool(h.toolEditMessage(), h.handleEditMessage)
- mcpServer.AddTool(h.toolRevokeMessage(), h.handleRevokeMessage)
- mcpServer.AddTool(h.toolDeleteMessage(), h.handleDeleteMessage)
- mcpServer.AddTool(h.toolMarkAsRead(), h.handleMarkAsRead)
- mcpServer.AddTool(h.toolStarMessage(), h.handleStarMessage)
-}
-
-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) {
- ctx, err := mcpHelpers.ContextWithDefaultDevice(ctx)
- if err != nil {
- return nil, err
- }
-
- 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) {
- ctx, err := mcpHelpers.ContextWithDefaultDevice(ctx)
- if err != nil {
- return nil, err
- }
-
- 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) {
- ctx, err := mcpHelpers.ContextWithDefaultDevice(ctx)
- if err != nil {
- return nil, err
- }
-
- 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) {
- ctx, err := mcpHelpers.ContextWithDefaultDevice(ctx)
- if err != nil {
- return nil, err
- }
-
- 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)
- }
-}
-
-func (h *QueryHandler) toolArchiveChat() mcp.Tool {
- return mcp.NewTool(
- "whatsapp_archive_chat",
- mcp.WithDescription("Archive or unarchive a WhatsApp chat. Archived chats are hidden from the main chat list."),
- mcp.WithTitleAnnotation("Archive/Unarchive Chat"),
- mcp.WithReadOnlyHintAnnotation(false),
- 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.WithBoolean("archived",
- mcp.Description("Set to true to archive the chat, false to unarchive it."),
- mcp.Required(),
- ),
- )
-}
-
-func (h *QueryHandler) handleArchiveChat(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
- ctx, err := mcpHelpers.ContextWithDefaultDevice(ctx)
- if err != nil {
- return nil, err
- }
-
- chatJID, err := request.RequireString("chat_jid")
- if err != nil {
- return nil, err
- }
-
- args := request.GetArguments()
- if args == nil {
- return nil, fmt.Errorf("missing required argument: archived")
- }
-
- archivedValue, ok := args["archived"]
- if !ok {
- return nil, fmt.Errorf("missing required argument: archived")
- }
-
- archived, err := toBool(archivedValue)
- if err != nil {
- return nil, err
- }
-
- req := domainChat.ArchiveChatRequest{
- ChatJID: chatJID,
- Archived: archived,
- }
-
- resp, err := h.chatService.ArchiveChat(ctx, req)
- if err != nil {
- return nil, err
- }
-
- fallback := resp.Message
- return mcp.NewToolResultStructured(resp, fallback), nil
-}
-
-func (h *QueryHandler) toolReactMessage() mcp.Tool {
- return mcp.NewTool(
- "whatsapp_react_message",
- mcp.WithDescription("React to a WhatsApp message with an emoji. Send an empty string as emoji to remove an existing reaction."),
- mcp.WithTitleAnnotation("React to Message"),
- mcp.WithReadOnlyHintAnnotation(false),
- mcp.WithDestructiveHintAnnotation(false),
- mcp.WithIdempotentHintAnnotation(false),
- mcp.WithString("phone",
- mcp.Required(),
- mcp.Description("Phone number or group JID of the chat containing the message"),
- ),
- mcp.WithString("message_id",
- mcp.Required(),
- mcp.Description("The WhatsApp message ID to react to"),
- ),
- mcp.WithString("emoji",
- mcp.Description("Emoji to react with. Pass an empty string to remove an existing reaction."),
- ),
- )
-}
-
-func (h *QueryHandler) handleReactMessage(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
- ctx, err := mcpHelpers.ContextWithDefaultDevice(ctx)
- if err != nil {
- return nil, err
- }
-
- phone, err := request.RequireString("phone")
- if err != nil {
- return nil, err
- }
- utils.SanitizePhone(&phone)
-
- messageID, err := request.RequireString("message_id")
- if err != nil {
- return nil, err
- }
-
- emoji := request.GetString("emoji", "")
-
- resp, err := h.messageService.ReactMessage(ctx, domainMessage.ReactionRequest{
- MessageID: messageID,
- Phone: phone,
- Emoji: emoji,
- })
- if err != nil {
- return nil, err
- }
-
- fallback := fmt.Sprintf("Reaction sent (message ID: %s)", resp.MessageID)
- return mcp.NewToolResultStructured(resp, fallback), nil
-}
-
-func (h *QueryHandler) toolEditMessage() mcp.Tool {
- return mcp.NewTool(
- "whatsapp_edit_message",
- mcp.WithDescription("Edit a previously sent WhatsApp message. Note: only works within approximately 15 minutes of the original send (WhatsApp protocol limit)."),
- mcp.WithTitleAnnotation("Edit Message"),
- mcp.WithReadOnlyHintAnnotation(false),
- mcp.WithDestructiveHintAnnotation(false),
- mcp.WithIdempotentHintAnnotation(false),
- mcp.WithString("phone",
- mcp.Required(),
- mcp.Description("Phone number or group JID of the chat containing the message"),
- ),
- mcp.WithString("message_id",
- mcp.Required(),
- mcp.Description("The WhatsApp message ID to edit"),
- ),
- mcp.WithString("message",
- mcp.Required(),
- mcp.Description("The new text content to replace the original message with"),
- ),
- )
-}
-
-func (h *QueryHandler) handleEditMessage(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
- ctx, err := mcpHelpers.ContextWithDefaultDevice(ctx)
- if err != nil {
- return nil, err
- }
-
- phone, err := request.RequireString("phone")
- if err != nil {
- return nil, err
- }
- utils.SanitizePhone(&phone)
-
- messageID, err := request.RequireString("message_id")
- if err != nil {
- return nil, err
- }
-
- message, err := request.RequireString("message")
- if err != nil {
- return nil, err
- }
-
- resp, err := h.messageService.UpdateMessage(ctx, domainMessage.UpdateMessageRequest{
- MessageID: messageID,
- Phone: phone,
- Message: message,
- })
- if err != nil {
- return nil, err
- }
-
- fallback := fmt.Sprintf("Message edited (ID: %s)", resp.MessageID)
- return mcp.NewToolResultStructured(resp, fallback), nil
-}
-
-func (h *QueryHandler) toolRevokeMessage() mcp.Tool {
- return mcp.NewTool(
- "whatsapp_revoke_message",
- mcp.WithDescription("Delete a WhatsApp message for EVERYONE in the chat (destructive — cannot be undone)."),
- mcp.WithTitleAnnotation("Revoke Message (Delete for Everyone)"),
- mcp.WithReadOnlyHintAnnotation(false),
- mcp.WithDestructiveHintAnnotation(true),
- mcp.WithIdempotentHintAnnotation(false),
- mcp.WithString("phone",
- mcp.Required(),
- mcp.Description("Phone number or group JID of the chat containing the message"),
- ),
- mcp.WithString("message_id",
- mcp.Required(),
- mcp.Description("The WhatsApp message ID to delete for everyone"),
- ),
- )
-}
-
-func (h *QueryHandler) handleRevokeMessage(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
- ctx, err := mcpHelpers.ContextWithDefaultDevice(ctx)
- if err != nil {
- return nil, err
- }
-
- phone, err := request.RequireString("phone")
- if err != nil {
- return nil, err
- }
- utils.SanitizePhone(&phone)
-
- messageID, err := request.RequireString("message_id")
- if err != nil {
- return nil, err
- }
-
- resp, err := h.messageService.RevokeMessage(ctx, domainMessage.RevokeRequest{
- MessageID: messageID,
- Phone: phone,
- })
- if err != nil {
- return nil, err
- }
-
- fallback := fmt.Sprintf("Message revoked (ID: %s)", resp.MessageID)
- return mcp.NewToolResultStructured(resp, fallback), nil
-}
-
-func (h *QueryHandler) toolDeleteMessage() mcp.Tool {
- return mcp.NewTool(
- "whatsapp_delete_message",
- mcp.WithDescription("Delete a WhatsApp message for ME only (local delete — the other party can still see it). Destructive."),
- mcp.WithTitleAnnotation("Delete Message (For Me)"),
- mcp.WithReadOnlyHintAnnotation(false),
- mcp.WithDestructiveHintAnnotation(true),
- mcp.WithIdempotentHintAnnotation(false),
- mcp.WithString("phone",
- mcp.Required(),
- mcp.Description("Phone number or group JID of the chat containing the message"),
- ),
- mcp.WithString("message_id",
- mcp.Required(),
- mcp.Description("The WhatsApp message ID to delete locally"),
- ),
- )
-}
-
-func (h *QueryHandler) handleDeleteMessage(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
- ctx, err := mcpHelpers.ContextWithDefaultDevice(ctx)
- if err != nil {
- return nil, err
- }
-
- phone, err := request.RequireString("phone")
- if err != nil {
- return nil, err
- }
- utils.SanitizePhone(&phone)
-
- messageID, err := request.RequireString("message_id")
- if err != nil {
- return nil, err
- }
-
- if err := h.messageService.DeleteMessage(ctx, domainMessage.DeleteRequest{
- MessageID: messageID,
- Phone: phone,
- }); err != nil {
- return nil, err
- }
-
- return mcp.NewToolResultText(fmt.Sprintf("Message %s deleted", messageID)), nil
-}
-
-func (h *QueryHandler) toolMarkAsRead() mcp.Tool {
- return mcp.NewTool(
- "whatsapp_mark_as_read",
- mcp.WithDescription("Mark a WhatsApp message as read, sending a read receipt to the sender."),
- mcp.WithTitleAnnotation("Mark Message as Read"),
- mcp.WithReadOnlyHintAnnotation(false),
- mcp.WithDestructiveHintAnnotation(false),
- mcp.WithIdempotentHintAnnotation(true),
- mcp.WithString("phone",
- mcp.Required(),
- mcp.Description("Phone number or group JID of the chat containing the message"),
- ),
- mcp.WithString("message_id",
- mcp.Required(),
- mcp.Description("The WhatsApp message ID to mark as read"),
- ),
- )
-}
-
-func (h *QueryHandler) handleMarkAsRead(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
- ctx, err := mcpHelpers.ContextWithDefaultDevice(ctx)
- if err != nil {
- return nil, err
- }
-
- phone, err := request.RequireString("phone")
- if err != nil {
- return nil, err
- }
- utils.SanitizePhone(&phone)
-
- messageID, err := request.RequireString("message_id")
- if err != nil {
- return nil, err
- }
-
- resp, err := h.messageService.MarkAsRead(ctx, domainMessage.MarkAsReadRequest{
- MessageID: messageID,
- Phone: phone,
- })
- if err != nil {
- return nil, err
- }
-
- fallback := fmt.Sprintf("Message marked as read (ID: %s)", resp.MessageID)
- return mcp.NewToolResultStructured(resp, fallback), nil
-}
-
-func (h *QueryHandler) toolStarMessage() mcp.Tool {
- return mcp.NewTool(
- "whatsapp_star_message",
- mcp.WithDescription("Star or unstar a WhatsApp message."),
- mcp.WithTitleAnnotation("Star/Unstar Message"),
- mcp.WithReadOnlyHintAnnotation(false),
- mcp.WithDestructiveHintAnnotation(false),
- mcp.WithIdempotentHintAnnotation(true),
- mcp.WithString("phone",
- mcp.Required(),
- mcp.Description("Phone number or group JID of the chat containing the message"),
- ),
- mcp.WithString("message_id",
- mcp.Required(),
- mcp.Description("The WhatsApp message ID to star or unstar"),
- ),
- mcp.WithBoolean("is_starred",
- mcp.Required(),
- mcp.Description("Set to true to star the message, false to unstar it"),
- ),
- )
-}
-
-func (h *QueryHandler) handleStarMessage(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
- ctx, err := mcpHelpers.ContextWithDefaultDevice(ctx)
- if err != nil {
- return nil, err
- }
-
- phone, err := request.RequireString("phone")
- if err != nil {
- return nil, err
- }
- utils.SanitizePhone(&phone)
-
- messageID, err := request.RequireString("message_id")
- if err != nil {
- return nil, err
- }
-
- args := request.GetArguments()
- if args == nil {
- return nil, fmt.Errorf("missing required argument: is_starred")
- }
- isStarredValue, ok := args["is_starred"]
- if !ok {
- return nil, fmt.Errorf("missing required argument: is_starred")
- }
- isStarred, err := toBool(isStarredValue)
- if err != nil {
- return nil, err
- }
-
- if err := h.messageService.StarMessage(ctx, domainMessage.StarRequest{
- MessageID: messageID,
- Phone: phone,
- IsStarred: isStarred,
- }); err != nil {
- return nil, err
- }
-
- return mcp.NewToolResultText(fmt.Sprintf("Message %s star=%t", messageID, isStarred)), nil
-}
diff --git a/src/ui/mcp/route.go b/src/ui/mcp/route.go
new file mode 100644
index 00000000..cdb094b5
--- /dev/null
+++ b/src/ui/mcp/route.go
@@ -0,0 +1,67 @@
+package mcp
+
+import (
+ "context"
+ "net/http"
+ "strings"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/ui/rest/middleware"
+ "github.com/gofiber/fiber/v3"
+ "github.com/gofiber/fiber/v3/middleware/adaptor"
+ "github.com/mark3labs/mcp-go/server"
+ "github.com/sirupsen/logrus"
+)
+
+// Register mounts the MCP streamable-HTTP endpoint at /mcp on the given
+// router (which already carries AppBasePath and the basic-auth middleware).
+//
+// Device scoping mirrors REST: the X-Device-Id header picks the device for
+// the connection (empty resolves the default device, same as
+// DeviceMiddleware); a per-call device_id tool argument overrides it (see
+// resolveDeviceContext).
+func Register(router fiber.Router, dm *whatsapp.DeviceManager, deps Deps) {
+ // dm is typed here, but handlers take the deviceResolver interface;
+ // a nil *DeviceManager must become a nil interface, not a typed nil.
+ var resolver deviceResolver
+ if dm != nil {
+ resolver = dm
+ }
+
+ httpServer := server.NewStreamableHTTPServer(
+ NewServer(deps, resolver),
+ // Stateless: no server-initiated notifications or subscriptions are
+ // used, and it avoids tying a session store to Fiber's shutdown.
+ server.WithStateLess(true),
+ // No server-initiated notifications are used, so the standalone GET
+ // SSE stream is never needed. Without this, a GET reaches mcp-go's
+ // "for { select { case <-writeChan: ...; case <-ctx.Done(): } }"
+ // loop; ctx there is the *fasthttp.RequestCtx, whose Done() channel
+ // only closes on server shutdown (not client disconnect), so the
+ // goroutine, the fasthttp body-stream writer, and the connection/FD
+ // would all be pinned forever through the fasthttp adaptor.
+ server.WithDisableStreaming(true),
+ server.WithHTTPContextFunc(func(ctx context.Context, r *http.Request) context.Context {
+ if dm == nil {
+ return ctx
+ }
+ deviceID := strings.TrimSpace(r.Header.Get(middleware.DeviceIDHeader))
+ inst, _, err := dm.ResolveDevice(deviceID)
+ if err != nil {
+ // Leave the context empty; handlers surface a tool error
+ // ("device identification required") on use.
+ logrus.Debugf("MCP device resolution failed for %q: %v", deviceID, err)
+ return ctx
+ }
+ return whatsapp.ContextWithDevice(ctx, inst)
+ }),
+ )
+
+ handler := adaptor.HTTPHandler(httpServer)
+ // POST carries JSON-RPC calls; DELETE is part of the streamable-HTTP
+ // session lifecycle. GET is intentionally not mounted: with streaming
+ // disabled mcp-go would just 405 it, so Fiber's own 404 for an
+ // unmounted method is equivalent and keeps the route surface narrow.
+ router.Post("/mcp", handler)
+ router.Delete("/mcp", handler)
+}
diff --git a/src/ui/mcp/schemas.go b/src/ui/mcp/schemas.go
new file mode 100644
index 00000000..1dc00572
--- /dev/null
+++ b/src/ui/mcp/schemas.go
@@ -0,0 +1,134 @@
+package mcp
+
+// Raw JSON Schemas for the consolidated tools. mcp-go validates tool calls
+// against these before handlers run (santhosh-tekuri/jsonschema/v6), so the
+// allOf/if/then conditionals are enforced, not advisory.
+
+const sendSchema = `{
+ "type": "object",
+ "required": ["type", "phone"],
+ "properties": {
+ "type": {"type": "string", "enum": ["text","image","video","audio","document","sticker","location","contact","poll","link","forward"], "description": "Kind of message to send"},
+ "phone": {"type": "string", "description": "Destination phone number or group JID"},
+ "device_id": {"type": "string", "description": "Act as this device instead of the connection default (X-Device-Id header)"},
+ "is_forwarded": {"type": "boolean", "description": "Mark the message as forwarded (default false)"},
+ "message": {"type": "string", "description": "type=text: the text body"},
+ "reply_message_id": {"type": "string", "description": "type=text: message ID to reply to"},
+ "mentions": {"type": "array", "items": {"type": "string"}, "description": "type=text: ghost mentions; \"@everyone\" mentions all group participants"},
+ "image_url": {"type": "string", "description": "type=image: URL of the image (fetched server-side)"},
+ "caption": {"type": "string", "description": "image/video/document/link: caption text"},
+ "view_once": {"type": "boolean", "description": "image/video: view-once message (default false)"},
+ "compress": {"type": "boolean", "description": "image (default true) / video (default false): re-encode before sending"},
+ "video_url": {"type": "string", "description": "type=video: URL of the video (mp4/mkv/avi, fetched server-side)"},
+ "gif_playback": {"type": "boolean", "description": "type=video: play as looping GIF (default false)"},
+ "audio_url": {"type": "string", "description": "type=audio: URL of the audio file (fetched server-side)"},
+ "ptt": {"type": "boolean", "description": "type=audio: send as voice note (requires ffmpeg server-side, default false)"},
+ "file_url": {"type": "string", "description": "type=document: URL of the file; MIME type and filename derived server-side"},
+ "sticker_url": {"type": "string", "description": "type=sticker: URL of an image to convert to a WebP sticker"},
+ "latitude": {"type": "string", "description": "type=location: latitude as string"},
+ "longitude": {"type": "string", "description": "type=location: longitude as string"},
+ "contact_name": {"type": "string", "description": "type=contact: contact display name"},
+ "contact_phone": {"type": "string", "description": "type=contact: contact phone number"},
+ "question": {"type": "string", "description": "type=poll: the poll question"},
+ "options": {"type": "array", "items": {"type": "string"}, "minItems": 2, "description": "type=poll: poll options (min 2)"},
+ "max_answer": {"type": "integer", "description": "type=poll: max selectable options (default 1)"},
+ "link": {"type": "string", "description": "type=link: the URL to send"},
+ "message_id": {"type": "string", "description": "type=forward: source message ID from chat storage"},
+ "duration": {"type": "integer", "description": "type=forward: disappearing duration seconds (0, 86400, 604800, 7776000)"},
+ "force_reupload": {"type": "boolean", "description": "type=forward: re-upload media instead of reusing references (default false)"}
+ },
+ "allOf": [
+ {"if": {"properties": {"type": {"const": "text"}}}, "then": {"required": ["message"]}},
+ {"if": {"properties": {"type": {"const": "image"}}}, "then": {"required": ["image_url"]}},
+ {"if": {"properties": {"type": {"const": "video"}}}, "then": {"required": ["video_url"]}},
+ {"if": {"properties": {"type": {"const": "audio"}}}, "then": {"required": ["audio_url"]}},
+ {"if": {"properties": {"type": {"const": "document"}}}, "then": {"required": ["file_url"]}},
+ {"if": {"properties": {"type": {"const": "sticker"}}}, "then": {"required": ["sticker_url"]}},
+ {"if": {"properties": {"type": {"const": "location"}}}, "then": {"required": ["latitude", "longitude"]}},
+ {"if": {"properties": {"type": {"const": "contact"}}}, "then": {"required": ["contact_name", "contact_phone"]}},
+ {"if": {"properties": {"type": {"const": "poll"}}}, "then": {"required": ["question", "options"]}},
+ {"if": {"properties": {"type": {"const": "link"}}}, "then": {"required": ["link", "caption"]}},
+ {"if": {"properties": {"type": {"const": "forward"}}}, "then": {"required": ["message_id"]}}
+ ]
+}`
+
+const messageSchema = `{
+ "type": "object",
+ "required": ["action", "phone", "message_id"],
+ "properties": {
+ "action": {"type": "string", "enum": ["react","edit","revoke","delete","mark_read","star","unstar","download_media"], "description": "Operation on an existing message. revoke = delete for everyone (destructive); delete = delete for me only; download_media returns the local file path"},
+ "phone": {"type": "string", "description": "Phone number or group JID of the chat containing the message"},
+ "message_id": {"type": "string", "description": "The WhatsApp message ID"},
+ "device_id": {"type": "string", "description": "Act as this device instead of the connection default"},
+ "emoji": {"type": "string", "description": "action=react: emoji to react with; empty string removes the reaction"},
+ "message": {"type": "string", "description": "action=edit: replacement text (works ~15 minutes after send)"}
+ },
+ "allOf": [
+ {"if": {"properties": {"action": {"const": "edit"}}}, "then": {"required": ["message"]}}
+ ]
+}`
+
+const chatSchema = `{
+ "type": "object",
+ "required": ["action"],
+ "properties": {
+ "action": {"type": "string", "enum": ["list_chats","list_contacts","get_messages","archive"], "description": "Chat/contact query or archive toggle"},
+ "device_id": {"type": "string", "description": "Act as this device instead of the connection default"},
+ "chat_jid": {"type": "string", "description": "get_messages/archive: chat JID (e.g. [email protected] or [email protected])"},
+ "limit": {"type": "integer", "description": "list_chats (default 25) / get_messages (default 50): max rows"},
+ "offset": {"type": "integer", "description": "list_chats/get_messages: rows to skip (default 0)"},
+ "search": {"type": "string", "description": "list_chats: filter by chat name; get_messages: full-text search"},
+ "has_media": {"type": "boolean", "description": "list_chats: only chats containing media"},
+ "start_time": {"type": "string", "description": "get_messages: only messages after this RFC3339 timestamp"},
+ "end_time": {"type": "string", "description": "get_messages: only messages before this RFC3339 timestamp"},
+ "media_only": {"type": "boolean", "description": "get_messages: only media messages"},
+ "is_from_me": {"type": "boolean", "description": "get_messages: filter by sender (true = sent by me)"},
+ "archived": {"type": "boolean", "description": "archive: true to archive, false to unarchive"}
+ },
+ "allOf": [
+ {"if": {"properties": {"action": {"const": "get_messages"}}}, "then": {"required": ["chat_jid"]}},
+ {"if": {"properties": {"action": {"const": "archive"}}}, "then": {"required": ["chat_jid", "archived"]}}
+ ]
+}`
+
+const groupSchema = `{
+ "type": "object",
+ "required": ["action"],
+ "properties": {
+ "action": {"type": "string", "enum": ["create","join_with_link","leave","info","participants","add_participants","remove_participants","promote","demote","invite_link","set_name","set_topic","set_settings","join_requests","manage_join_requests"], "description": "Group operation"},
+ "device_id": {"type": "string", "description": "Act as this device instead of the connection default"},
+ "group_id": {"type": "string", "description": "Group JID or numeric ID (all actions except create/join_with_link)"},
+ "title": {"type": "string", "description": "create: group subject"},
+ "participants": {"type": "array", "items": {"type": "string"}, "description": "create (optional) / add_participants / remove_participants / promote / demote / manage_join_requests: phone numbers without suffix"},
+ "invite_link": {"type": "string", "description": "join_with_link: WhatsApp invite link"},
+ "reset": {"type": "boolean", "description": "invite_link: revoke and regenerate the link (default false)"},
+ "name": {"type": "string", "description": "set_name: new group name"},
+ "topic": {"type": "string", "description": "set_topic: new topic/description"},
+ "announce": {"type": "boolean", "description": "set_settings: true = only admins can send"},
+ "locked": {"type": "boolean", "description": "set_settings: true = only admins can edit group info"},
+ "request_action": {"type": "string", "enum": ["approve","reject"], "description": "manage_join_requests: what to do with the listed requesters"}
+ },
+ "allOf": [
+ {"if": {"properties": {"action": {"const": "create"}}}, "then": {"required": ["title"]}},
+ {"if": {"properties": {"action": {"const": "join_with_link"}}}, "then": {"required": ["invite_link"]}},
+ {"if": {"properties": {"action": {"enum": ["leave","info","participants","invite_link","join_requests"]}}}, "then": {"required": ["group_id"]}},
+ {"if": {"properties": {"action": {"enum": ["add_participants","remove_participants","promote","demote"]}}}, "then": {"required": ["group_id", "participants"]}},
+ {"if": {"properties": {"action": {"const": "set_name"}}}, "then": {"required": ["group_id", "name"]}},
+ {"if": {"properties": {"action": {"const": "set_topic"}}}, "then": {"required": ["group_id", "topic"]}},
+ {"if": {"properties": {"action": {"const": "set_settings"}}}, "then": {"required": ["group_id"], "anyOf": [{"required": ["announce"]}, {"required": ["locked"]}]}},
+ {"if": {"properties": {"action": {"const": "manage_join_requests"}}}, "then": {"required": ["group_id", "participants", "request_action"]}}
+ ]
+}`
+
+const appSchema = `{
+ "type": "object",
+ "required": ["action"],
+ "properties": {
+ "action": {"type": "string", "enum": ["status","login_qr","login_code","logout","reconnect"], "description": "Connection/session operation. login_qr returns a QR image; logout clears stored credentials (destructive)"},
+ "device_id": {"type": "string", "description": "Act as this device instead of the connection default"},
+ "phone": {"type": "string", "description": "login_code: phone number in international format (e.g. +628123456789)"}
+ },
+ "allOf": [
+ {"if": {"properties": {"action": {"const": "login_code"}}}, "then": {"required": ["phone"]}}
+ ]
+}`
diff --git a/src/ui/mcp/schemas_test.go b/src/ui/mcp/schemas_test.go
new file mode 100644
index 00000000..5a20aa0b
--- /dev/null
+++ b/src/ui/mcp/schemas_test.go
@@ -0,0 +1,138 @@
+package mcp
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/santhosh-tekuri/jsonschema/v6"
+ "github.com/stretchr/testify/require"
+)
+
+func compileSchema(t *testing.T, raw string) *jsonschema.Schema {
+ t.Helper()
+ doc, err := jsonschema.UnmarshalJSON(strings.NewReader(raw))
+ require.NoError(t, err)
+ c := jsonschema.NewCompiler()
+ require.NoError(t, c.AddResource("schema.json", doc))
+ s, err := c.Compile("schema.json")
+ require.NoError(t, err)
+ return s
+}
+
+func validate(t *testing.T, s *jsonschema.Schema, payload string) error {
+ t.Helper()
+ v, err := jsonschema.UnmarshalJSON(strings.NewReader(payload))
+ require.NoError(t, err)
+ return s.Validate(v)
+}
+
+func TestSchemas(t *testing.T) {
+ tests := []struct {
+ name string
+ schema string
+ payload string
+ wantErr bool
+ }{
+ // ---- whatsapp_send ----
+ {"send text ok", sendSchema, `{"type":"text","phone":"628","message":"hi"}`, false},
+ {"send text missing message", sendSchema, `{"type":"text","phone":"628"}`, true},
+ {"send missing phone", sendSchema, `{"type":"text","message":"hi"}`, true},
+ {"send bad type", sendSchema, `{"type":"fax","phone":"628"}`, true},
+ {"send image ok", sendSchema, `{"type":"image","phone":"628","image_url":"http://x/a.png","caption":"c"}`, false},
+ {"send image missing url", sendSchema, `{"type":"image","phone":"628"}`, true},
+ {"send video ok", sendSchema, `{"type":"video","phone":"628","video_url":"http://x/a.mp4"}`, false},
+ {"send video missing url", sendSchema, `{"type":"video","phone":"628"}`, true},
+ {"send audio ok", sendSchema, `{"type":"audio","phone":"628","audio_url":"http://x/a.ogg","ptt":true}`, false},
+ {"send audio missing url", sendSchema, `{"type":"audio","phone":"628"}`, true},
+ {"send document ok", sendSchema, `{"type":"document","phone":"628","file_url":"http://x/a.pdf"}`, false},
+ {"send document missing url", sendSchema, `{"type":"document","phone":"628"}`, true},
+ {"send sticker ok", sendSchema, `{"type":"sticker","phone":"628","sticker_url":"http://x/a.png"}`, false},
+ {"send sticker missing url", sendSchema, `{"type":"sticker","phone":"628"}`, true},
+ {"send location ok", sendSchema, `{"type":"location","phone":"628","latitude":"-6.2","longitude":"106.8"}`, false},
+ {"send location missing lng", sendSchema, `{"type":"location","phone":"628","latitude":"-6.2"}`, true},
+ {"send contact ok", sendSchema, `{"type":"contact","phone":"628","contact_name":"A","contact_phone":"629"}`, false},
+ {"send contact missing name", sendSchema, `{"type":"contact","phone":"628","contact_phone":"629"}`, true},
+ {"send poll ok", sendSchema, `{"type":"poll","phone":"628","question":"q","options":["a","b"]}`, false},
+ {"send poll one option", sendSchema, `{"type":"poll","phone":"628","question":"q","options":["a"]}`, true},
+ {"send link ok", sendSchema, `{"type":"link","phone":"628","link":"http://x","caption":"c"}`, false},
+ {"send link missing caption", sendSchema, `{"type":"link","phone":"628","link":"http://x"}`, true},
+ {"send forward ok", sendSchema, `{"type":"forward","phone":"628","message_id":"M1"}`, false},
+ {"send forward missing id", sendSchema, `{"type":"forward","phone":"628"}`, true},
+ {"send with device_id", sendSchema, `{"type":"text","phone":"628","message":"hi","device_id":"dev2"}`, false},
+
+ // ---- whatsapp_message ----
+ {"msg react ok", messageSchema, `{"action":"react","phone":"628","message_id":"M1","emoji":"👍"}`, false},
+ {"msg react no emoji ok (removes reaction)", messageSchema, `{"action":"react","phone":"628","message_id":"M1"}`, false},
+ {"msg edit ok", messageSchema, `{"action":"edit","phone":"628","message_id":"M1","message":"new"}`, false},
+ {"msg edit missing message", messageSchema, `{"action":"edit","phone":"628","message_id":"M1"}`, true},
+ {"msg revoke ok", messageSchema, `{"action":"revoke","phone":"628","message_id":"M1"}`, false},
+ {"msg delete ok", messageSchema, `{"action":"delete","phone":"628","message_id":"M1"}`, false},
+ {"msg mark_read ok", messageSchema, `{"action":"mark_read","phone":"628","message_id":"M1"}`, false},
+ {"msg star ok", messageSchema, `{"action":"star","phone":"628","message_id":"M1"}`, false},
+ {"msg unstar ok", messageSchema, `{"action":"unstar","phone":"628","message_id":"M1"}`, false},
+ {"msg download_media ok", messageSchema, `{"action":"download_media","phone":"628","message_id":"M1"}`, false},
+ {"msg missing message_id", messageSchema, `{"action":"react","phone":"628"}`, true},
+ {"msg bad action", messageSchema, `{"action":"pin","phone":"628","message_id":"M1"}`, true},
+
+ // ---- whatsapp_chat ----
+ {"chat list_chats ok", chatSchema, `{"action":"list_chats","limit":10,"search":"bob"}`, false},
+ {"chat list_contacts ok", chatSchema, `{"action":"list_contacts"}`, false},
+ {"chat get_messages ok", chatSchema, `{"action":"get_messages","chat_jid":"[email protected]","media_only":true}`, false},
+ {"chat get_messages missing jid", chatSchema, `{"action":"get_messages"}`, true},
+ {"chat archive ok", chatSchema, `{"action":"archive","chat_jid":"[email protected]","archived":true}`, false},
+ {"chat archive missing flag", chatSchema, `{"action":"archive","chat_jid":"[email protected]"}`, true},
+ {"chat bad action", chatSchema, `{"action":"nuke"}`, true},
+
+ // ---- whatsapp_group ----
+ {"group create ok", groupSchema, `{"action":"create","title":"T","participants":["628"]}`, false},
+ {"group create missing title", groupSchema, `{"action":"create"}`, true},
+ {"group join ok", groupSchema, `{"action":"join_with_link","invite_link":"http://chat.whatsapp.com/x"}`, false},
+ {"group join missing link", groupSchema, `{"action":"join_with_link"}`, true},
+ {"group leave ok", groupSchema, `{"action":"leave","group_id":"[email protected]"}`, false},
+ {"group leave missing id", groupSchema, `{"action":"leave"}`, true},
+ {"group info ok", groupSchema, `{"action":"info","group_id":"[email protected]"}`, false},
+ {"group participants ok", groupSchema, `{"action":"participants","group_id":"[email protected]"}`, false},
+ {"group add ok", groupSchema, `{"action":"add_participants","group_id":"[email protected]","participants":["628"]}`, false},
+ {"group add missing participants", groupSchema, `{"action":"add_participants","group_id":"[email protected]"}`, true},
+ {"group remove ok", groupSchema, `{"action":"remove_participants","group_id":"[email protected]","participants":["628"]}`, false},
+ {"group promote ok", groupSchema, `{"action":"promote","group_id":"[email protected]","participants":["628"]}`, false},
+ {"group demote ok", groupSchema, `{"action":"demote","group_id":"[email protected]","participants":["628"]}`, false},
+ {"group invite_link ok", groupSchema, `{"action":"invite_link","group_id":"[email protected]","reset":true}`, false},
+ {"group set_name ok", groupSchema, `{"action":"set_name","group_id":"[email protected]","name":"N"}`, false},
+ {"group set_name missing name", groupSchema, `{"action":"set_name","group_id":"[email protected]"}`, true},
+ {"group set_topic ok", groupSchema, `{"action":"set_topic","group_id":"[email protected]","topic":"T"}`, false},
+ {"group set_settings announce", groupSchema, `{"action":"set_settings","group_id":"[email protected]","announce":true}`, false},
+ {"group set_settings locked", groupSchema, `{"action":"set_settings","group_id":"[email protected]","locked":false}`, false},
+ {"group set_settings neither", groupSchema, `{"action":"set_settings","group_id":"[email protected]"}`, true},
+ {"group join_requests ok", groupSchema, `{"action":"join_requests","group_id":"[email protected]"}`, false},
+ {"group manage_join_requests ok", groupSchema, `{"action":"manage_join_requests","group_id":"[email protected]","participants":["628"],"request_action":"approve"}`, false},
+ {"group manage_join_requests bad verb", groupSchema, `{"action":"manage_join_requests","group_id":"[email protected]","participants":["628"],"request_action":"ban"}`, true},
+ {"group manage_join_requests missing verb", groupSchema, `{"action":"manage_join_requests","group_id":"[email protected]","participants":["628"]}`, true},
+
+ // ---- whatsapp_app ----
+ {"app status ok", appSchema, `{"action":"status"}`, false},
+ {"app login_qr ok", appSchema, `{"action":"login_qr"}`, false},
+ {"app login_code ok", appSchema, `{"action":"login_code","phone":"+628123"}`, false},
+ {"app login_code missing phone", appSchema, `{"action":"login_code"}`, true},
+ {"app logout ok", appSchema, `{"action":"logout"}`, false},
+ {"app reconnect ok", appSchema, `{"action":"reconnect"}`, false},
+ {"app bad action", appSchema, `{"action":"restart"}`, true},
+ }
+
+ // compile each schema once
+ compiled := map[string]*jsonschema.Schema{}
+ for _, raw := range []string{sendSchema, messageSchema, chatSchema, groupSchema, appSchema} {
+ compiled[raw] = compileSchema(t, raw)
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ err := validate(t, compiled[tt.schema], tt.payload)
+ if tt.wantErr {
+ require.Error(t, err)
+ } else {
+ require.NoError(t, err)
+ }
+ })
+ }
+}
diff --git a/src/ui/mcp/send.go b/src/ui/mcp/send.go
index b23222b0..57869553 100644
--- a/src/ui/mcp/send.go
+++ b/src/ui/mcp/send.go
@@ -2,729 +2,151 @@ package mcp
import (
"context"
- "errors"
+ "encoding/json"
"fmt"
domainSend "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/send"
- mcpHelpers "github.com/aldinokemal/go-whatsapp-web-multidevice/ui/mcp/helpers"
- "github.com/mark3labs/mcp-go/mcp"
+ mcpg "github.com/mark3labs/mcp-go/mcp"
"github.com/mark3labs/mcp-go/server"
)
type SendHandler struct {
sendService domainSend.ISendUsecase
+ resolver deviceResolver
}
-func InitMcpSend(sendService domainSend.ISendUsecase) *SendHandler {
- return &SendHandler{
- sendService: sendService,
- }
+func InitMcpSend(sendService domainSend.ISendUsecase, resolver deviceResolver) *SendHandler {
+ return &SendHandler{sendService: sendService, resolver: resolver}
}
func (s *SendHandler) AddSendTools(mcpServer *server.MCPServer) {
- mcpServer.AddTool(s.toolSendText(), s.handleSendText)
- mcpServer.AddTool(s.toolSendContact(), s.handleSendContact)
- mcpServer.AddTool(s.toolSendLink(), s.handleSendLink)
- mcpServer.AddTool(s.toolSendLocation(), s.handleSendLocation)
- mcpServer.AddTool(s.toolSendImage(), s.handleSendImage)
- mcpServer.AddTool(s.toolSendVideo(), s.handleSendVideo)
- mcpServer.AddTool(s.toolSendSticker(), s.handleSendSticker)
- mcpServer.AddTool(s.toolSendDocument(), s.handleSendDocument)
- mcpServer.AddTool(s.toolSendAudio(), s.handleSendAudio)
- mcpServer.AddTool(s.toolSendPoll(), s.handleSendPoll)
- mcpServer.AddTool(s.toolForwardMessage(), s.handleForwardMessage)
-}
-
-func (s *SendHandler) toolSendText() mcp.Tool {
- sendTextTool := mcp.NewTool("whatsapp_send_text",
- mcp.WithDescription("Send a text message to a WhatsApp contact or group. Supports ghost mentions (mention users without showing @phone in message text)."),
- mcp.WithTitleAnnotation("Send Text Message"),
- mcp.WithReadOnlyHintAnnotation(false),
- mcp.WithDestructiveHintAnnotation(false),
- mcp.WithIdempotentHintAnnotation(false),
- mcp.WithString("phone",
- mcp.Required(),
- mcp.Description("Phone number or group ID to send message to"),
- ),
- mcp.WithString("message",
- mcp.Required(),
- mcp.Description("The text message to send."),
- ),
- mcp.WithBoolean("is_forwarded",
- mcp.Description("Whether this message is being forwarded (default: false)"),
- ),
- mcp.WithString("reply_message_id",
- mcp.Description("Message ID to reply to (optional)"),
- ),
- mcp.WithArray("mentions",
- mcp.Description("List of phone numbers or JIDs to mention (ghost mentions - users will be notified but @phone won't appear in message text). Use \"@everyone\" to mention all group participants. Example: [\"628123456789\", \"@everyone\"]"),
- ),
- )
-
- return sendTextTool
-}
-
-func (s *SendHandler) handleSendText(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
- ctx, err := mcpHelpers.ContextWithDefaultDevice(ctx)
- if err != nil {
- return nil, err
- }
-
- phone, err := request.RequireString("phone")
- if err != nil {
- return nil, err
- }
-
- message, err := request.RequireString("message")
- if err != nil {
- return nil, err
- }
-
- replyMessageId := request.GetString("reply_message_id", "")
- mentions := request.GetStringSlice("mentions", nil)
-
- res, err := s.sendService.SendText(ctx, domainSend.MessageRequest{
- BaseRequest: domainSend.BaseRequest{
- Phone: phone,
- IsForwarded: request.GetBool("is_forwarded", false),
- },
- Message: message,
- ReplyMessageID: &replyMessageId,
- Mentions: mentions,
- })
-
- if err != nil {
- return nil, err
- }
-
- return mcp.NewToolResultText(fmt.Sprintf("Message sent successfully with ID %s", res.MessageID)), nil
-}
-
-func (s *SendHandler) toolSendContact() mcp.Tool {
- sendContactTool := mcp.NewTool("whatsapp_send_contact",
- mcp.WithDescription("Send a contact card to a WhatsApp contact or group."),
- mcp.WithTitleAnnotation("Send Contact"),
- mcp.WithReadOnlyHintAnnotation(false),
- mcp.WithDestructiveHintAnnotation(false),
- mcp.WithIdempotentHintAnnotation(false),
- mcp.WithString("phone",
- mcp.Required(),
- mcp.Description("Phone number or group ID to send contact to"),
- ),
- mcp.WithString("contact_name",
- mcp.Required(),
- mcp.Description("Name of the contact to send"),
- ),
- mcp.WithString("contact_phone",
- mcp.Required(),
- mcp.Description("Phone number of the contact to send"),
- ),
- mcp.WithBoolean("is_forwarded",
- mcp.Description("Whether this message is being forwarded (default: false)"),
- ),
- )
-
- return sendContactTool
-}
-
-func (s *SendHandler) handleSendContact(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
- ctx, err := mcpHelpers.ContextWithDefaultDevice(ctx)
- if err != nil {
- return nil, err
- }
-
- phone, err := request.RequireString("phone")
- if err != nil {
- return nil, err
- }
-
- contactName, err := request.RequireString("contact_name")
- if err != nil {
- return nil, err
- }
-
- contactPhone, err := request.RequireString("contact_phone")
- if err != nil {
- return nil, err
- }
-
- res, err := s.sendService.SendContact(ctx, domainSend.ContactRequest{
- BaseRequest: domainSend.BaseRequest{
- Phone: phone,
- IsForwarded: request.GetBool("is_forwarded", false),
- },
- ContactName: contactName,
- ContactPhone: contactPhone,
- })
-
- if err != nil {
- return nil, err
- }
-
- return mcp.NewToolResultText(fmt.Sprintf("Contact sent successfully with ID %s", res.MessageID)), nil
-}
-
-func (s *SendHandler) toolSendLink() mcp.Tool {
- sendLinkTool := mcp.NewTool("whatsapp_send_link",
- mcp.WithDescription("Send a link with caption to a WhatsApp contact or group."),
- mcp.WithTitleAnnotation("Send Link"),
- mcp.WithReadOnlyHintAnnotation(false),
- mcp.WithDestructiveHintAnnotation(false),
- mcp.WithIdempotentHintAnnotation(false),
- mcp.WithString("phone",
- mcp.Required(),
- mcp.Description("Phone number or group ID to send link to"),
- ),
- mcp.WithString("link",
- mcp.Required(),
- mcp.Description("URL link to send"),
- ),
- mcp.WithString("caption",
- mcp.Required(),
- mcp.Description("Caption or description for the link"),
- ),
- mcp.WithBoolean("is_forwarded",
- mcp.Description("Whether this message is being forwarded (default: false)"),
- ),
+ tool := mcpg.NewTool("whatsapp_send",
+ mcpg.WithDescription("Send a WhatsApp message. The `type` field selects what to send: text, image, video, audio, document, sticker, location, contact, poll, link, or forward an existing message."),
+ mcpg.WithTitleAnnotation("Send WhatsApp Message"),
+ mcpg.WithReadOnlyHintAnnotation(false),
+ mcpg.WithDestructiveHintAnnotation(false),
+ mcpg.WithIdempotentHintAnnotation(false),
+ mcpg.WithRawInputSchema(json.RawMessage(sendSchema)),
)
-
- return sendLinkTool
+ // NewTool defaults InputSchema.Type to "object"; clear it so only
+ // RawInputSchema is set, or MarshalJSON rejects the tool as conflicting.
+ tool.InputSchema = mcpg.ToolInputSchema{}
+ mcpServer.AddTool(tool, s.handleSend)
}
-func (s *SendHandler) handleSendLink(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
- ctx, err := mcpHelpers.ContextWithDefaultDevice(ctx)
- if err != nil {
- return nil, err
- }
-
- phone, err := request.RequireString("phone")
+func (s *SendHandler) handleSend(ctx context.Context, request mcpg.CallToolRequest) (*mcpg.CallToolResult, error) {
+ ctx, _, err := resolveDeviceContext(ctx, request, s.resolver)
if err != nil {
- return nil, err
+ return mcpg.NewToolResultError(err.Error()), nil
}
- link, err := request.RequireString("link")
- if err != nil {
- return nil, err
- }
-
- res, err := s.sendService.SendLink(ctx, domainSend.LinkRequest{
- BaseRequest: domainSend.BaseRequest{
- Phone: phone,
- IsForwarded: request.GetBool("is_forwarded", false),
- },
- Link: link,
- Caption: request.GetString("caption", ""),
- })
-
+ msgType, err := request.RequireString("type")
if err != nil {
- return nil, err
+ return mcpg.NewToolResultError(err.Error()), nil
}
-
- return mcp.NewToolResultText(fmt.Sprintf("Link sent successfully with ID %s", res.MessageID)), nil
-}
-
-func (s *SendHandler) toolSendLocation() mcp.Tool {
- sendLocationTool := mcp.NewTool("whatsapp_send_location",
- mcp.WithDescription("Send a location coordinates to a WhatsApp contact or group."),
- mcp.WithTitleAnnotation("Send Location"),
- mcp.WithReadOnlyHintAnnotation(false),
- mcp.WithDestructiveHintAnnotation(false),
- mcp.WithIdempotentHintAnnotation(false),
- mcp.WithString("phone",
- mcp.Required(),
- mcp.Description("Phone number or group ID to send location to"),
- ),
- mcp.WithString("latitude",
- mcp.Required(),
- mcp.Description("Latitude coordinate (as string)"),
- ),
- mcp.WithString("longitude",
- mcp.Required(),
- mcp.Description("Longitude coordinate (as string)"),
- ),
- mcp.WithBoolean("is_forwarded",
- mcp.Description("Whether this message is being forwarded (default: false)"),
- ),
- )
-
- return sendLocationTool
-}
-
-func (s *SendHandler) handleSendLocation(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
- ctx, err := mcpHelpers.ContextWithDefaultDevice(ctx)
- if err != nil {
- return nil, err
- }
-
- phone, err := request.RequireString("phone")
- if err != nil {
- return nil, err
- }
-
- latitude, err := request.RequireString("latitude")
- if err != nil {
- return nil, err
- }
-
- longitude, err := request.RequireString("longitude")
- if err != nil {
- return nil, err
- }
-
- res, err := s.sendService.SendLocation(ctx, domainSend.LocationRequest{
- BaseRequest: domainSend.BaseRequest{
- Phone: phone,
- IsForwarded: request.GetBool("is_forwarded", false),
- },
- Latitude: latitude,
- Longitude: longitude,
- })
-
- if err != nil {
- return nil, err
- }
-
- return mcp.NewToolResultText(fmt.Sprintf("Location sent successfully with ID %s", res.MessageID)), nil
-}
-
-func (s *SendHandler) toolSendImage() mcp.Tool {
- sendImageTool := mcp.NewTool("whatsapp_send_image",
- mcp.WithDescription("Send an image to a WhatsApp contact or group."),
- mcp.WithTitleAnnotation("Send Image"),
- mcp.WithReadOnlyHintAnnotation(false),
- mcp.WithDestructiveHintAnnotation(false),
- mcp.WithIdempotentHintAnnotation(false),
- mcp.WithString("phone",
- mcp.Required(),
- mcp.Description("Phone number or group ID to send image to"),
- ),
- mcp.WithString("image_url",
- mcp.Description("URL of the image to send"),
- ),
- mcp.WithString("caption",
- mcp.Description("Caption or description for the image"),
- ),
- mcp.WithBoolean("view_once",
- mcp.Description("Whether this image should be viewed only once (default: false)"),
- ),
- mcp.WithBoolean("compress",
- mcp.Description("Whether to compress the image (default: true)"),
- ),
- mcp.WithBoolean("is_forwarded",
- mcp.Description("Whether this message is being forwarded (default: false)"),
- ),
- )
-
- return sendImageTool
-}
-
-func (s *SendHandler) handleSendImage(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
- ctx, err := mcpHelpers.ContextWithDefaultDevice(ctx)
- if err != nil {
- return nil, err
- }
-
- phone, err := request.RequireString("phone")
- if err != nil {
- return nil, err
- }
-
- imageURL, err := request.RequireString("image_url")
- if err != nil {
- return nil, err
- }
-
- imageRequest := domainSend.ImageRequest{
- BaseRequest: domainSend.BaseRequest{
- Phone: phone,
- IsForwarded: request.GetBool("is_forwarded", false),
- },
- Caption: request.GetString("caption", ""),
- ViewOnce: request.GetBool("view_once", false),
- Compress: request.GetBool("compress", true),
- }
-
- if imageURL != "" {
- imageRequest.ImageURL = &imageURL
- }
- res, err := s.sendService.SendImage(ctx, imageRequest)
- if err != nil {
- return nil, err
- }
-
- return mcp.NewToolResultText(fmt.Sprintf("Image sent successfully with ID %s", res.MessageID)), nil
-}
-
-func (s *SendHandler) toolSendSticker() mcp.Tool {
- sendStickerTool := mcp.NewTool("whatsapp_send_sticker",
- mcp.WithDescription("Send a sticker to a WhatsApp contact or group. Images are automatically converted to WebP sticker format."),
- mcp.WithTitleAnnotation("Send Sticker"),
- mcp.WithReadOnlyHintAnnotation(false),
- mcp.WithDestructiveHintAnnotation(false),
- mcp.WithIdempotentHintAnnotation(false),
- mcp.WithString("phone",
- mcp.Required(),
- mcp.Description("Phone number or group ID to send sticker to"),
- ),
- mcp.WithString("sticker_url",
- mcp.Description("URL of the image to convert to sticker and send"),
- ),
- mcp.WithBoolean("is_forwarded",
- mcp.Description("Whether this is a forwarded sticker"),
- ),
- )
-
- return sendStickerTool
-}
-
-func (s *SendHandler) handleSendSticker(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
- ctx, err := mcpHelpers.ContextWithDefaultDevice(ctx)
- if err != nil {
- return nil, err
- }
-
phone, err := request.RequireString("phone")
if err != nil {
- return nil, err
- }
-
- stickerURL := request.GetString("sticker_url", "")
- if stickerURL == "" {
- return nil, errors.New("sticker_url must be a non-empty string")
- }
-
- stickerRequest := domainSend.StickerRequest{
- BaseRequest: domainSend.BaseRequest{
- Phone: phone,
- IsForwarded: request.GetBool("is_forwarded", false),
- },
- StickerURL: &stickerURL,
- }
-
- res, err := s.sendService.SendSticker(ctx, stickerRequest)
- if err != nil {
- return nil, err
- }
-
- return mcp.NewToolResultText(fmt.Sprintf("Sticker sent successfully with ID %s", res.MessageID)), nil
-}
-
-func (s *SendHandler) toolSendVideo() mcp.Tool {
- sendVideoTool := mcp.NewTool("whatsapp_send_video",
- mcp.WithDescription("Send a video to a WhatsApp contact or group via a video URL (fetched server-side). Supports mp4/mkv/avi, max 30MB."),
- mcp.WithTitleAnnotation("Send Video"),
- mcp.WithReadOnlyHintAnnotation(false),
- mcp.WithDestructiveHintAnnotation(false),
- mcp.WithIdempotentHintAnnotation(false),
- mcp.WithString("phone",
- mcp.Required(),
- mcp.Description("Phone number or group ID to send video to"),
- ),
- mcp.WithString("video_url",
- mcp.Required(),
- mcp.Description("URL of the video to send (mp4/mkv/avi). The server downloads it before sending."),
- ),
- mcp.WithString("caption",
- mcp.Description("Caption or description for the video"),
- ),
- mcp.WithBoolean("view_once",
- mcp.Description("Whether this video should be viewed only once (default: false)"),
- ),
- mcp.WithBoolean("gif_playback",
- mcp.Description("Whether to play the video as a looping GIF (default: false)"),
- ),
- mcp.WithBoolean("compress",
- mcp.Description("Whether to re-encode/compress the video before sending (default: false)"),
- ),
- mcp.WithBoolean("is_forwarded",
- mcp.Description("Whether this message is being forwarded (default: false)"),
- ),
- )
-
- return sendVideoTool
-}
-
-func (s *SendHandler) handleSendVideo(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
- ctx, err := mcpHelpers.ContextWithDefaultDevice(ctx)
- if err != nil {
- return nil, err
- }
-
- phone, err := request.RequireString("phone")
- if err != nil {
- return nil, err
- }
-
- videoURL, err := request.RequireString("video_url")
- if err != nil {
- return nil, err
- }
- if videoURL == "" {
- return nil, errors.New("video_url must be a non-empty string")
- }
-
- videoRequest := domainSend.VideoRequest{
- BaseRequest: domainSend.BaseRequest{
- Phone: phone,
- IsForwarded: request.GetBool("is_forwarded", false),
- },
- Caption: request.GetString("caption", ""),
- ViewOnce: request.GetBool("view_once", false),
- GifPlayback: request.GetBool("gif_playback", false),
- Compress: request.GetBool("compress", false),
- VideoURL: &videoURL,
- }
-
- res, err := s.sendService.SendVideo(ctx, videoRequest)
- if err != nil {
- return nil, err
- }
-
- return mcp.NewToolResultText(fmt.Sprintf("Video sent successfully with ID %s", res.MessageID)), nil
-}
-
-func (s *SendHandler) toolSendDocument() mcp.Tool {
- return mcp.NewTool("whatsapp_send_document",
- mcp.WithDescription("Send a document/file to a WhatsApp contact or group via a URL fetched server-side. The MIME type and filename are derived server-side from the file URL."),
- mcp.WithTitleAnnotation("Send Document"),
- mcp.WithReadOnlyHintAnnotation(false),
- mcp.WithDestructiveHintAnnotation(false),
- mcp.WithIdempotentHintAnnotation(false),
- mcp.WithString("phone",
- mcp.Required(),
- mcp.Description("Phone number or group ID to send the document to"),
- ),
- mcp.WithString("file_url",
- mcp.Required(),
- mcp.Description("URL of the file to send. The server downloads and determines the MIME type and filename from this URL."),
- ),
- mcp.WithString("caption",
- mcp.Description("Optional caption for the document"),
- ),
- mcp.WithBoolean("is_forwarded",
- mcp.Description("Whether this message is being forwarded (default: false)"),
- ),
- )
-}
-
-func (s *SendHandler) handleSendDocument(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
- ctx, err := mcpHelpers.ContextWithDefaultDevice(ctx)
- if err != nil {
- return nil, err
- }
-
- phone, err := request.RequireString("phone")
- if err != nil {
- return nil, err
- }
-
- fileURL, err := request.RequireString("file_url")
- if err != nil {
- return nil, err
- }
- if fileURL == "" {
- return nil, errors.New("file_url must be a non-empty string")
- }
-
- res, err := s.sendService.SendFile(ctx, domainSend.FileRequest{
- BaseRequest: domainSend.BaseRequest{
- Phone: phone,
- IsForwarded: request.GetBool("is_forwarded", false),
- },
- FileURL: &fileURL,
- Caption: request.GetString("caption", ""),
- })
- if err != nil {
- return nil, err
- }
-
- return mcp.NewToolResultText(fmt.Sprintf("Document sent successfully with ID %s", res.MessageID)), nil
-}
-
-func (s *SendHandler) toolSendAudio() mcp.Tool {
- return mcp.NewTool("whatsapp_send_audio",
- mcp.WithDescription("Send an audio file to a WhatsApp contact or group via a URL fetched server-side."),
- mcp.WithTitleAnnotation("Send Audio"),
- mcp.WithReadOnlyHintAnnotation(false),
- mcp.WithDestructiveHintAnnotation(false),
- mcp.WithIdempotentHintAnnotation(false),
- mcp.WithString("phone",
- mcp.Required(),
- mcp.Description("Phone number or group ID to send the audio to"),
- ),
- mcp.WithString("audio_url",
- mcp.Required(),
- mcp.Description("URL of the audio file to send. The server downloads and sends it."),
- ),
- mcp.WithBoolean("ptt",
- mcp.Description("Send as a voice note (PTT). Requires ffmpeg server-side; transcodes to ogg/opus. (default: false)"),
- ),
- mcp.WithBoolean("is_forwarded",
- mcp.Description("Whether this message is being forwarded (default: false)"),
- ),
- )
-}
-
-func (s *SendHandler) handleSendAudio(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
- ctx, err := mcpHelpers.ContextWithDefaultDevice(ctx)
- if err != nil {
- return nil, err
- }
-
- phone, err := request.RequireString("phone")
- if err != nil {
- return nil, err
- }
-
- audioURL, err := request.RequireString("audio_url")
- if err != nil {
- return nil, err
- }
- if audioURL == "" {
- return nil, errors.New("audio_url must be a non-empty string")
- }
-
- res, err := s.sendService.SendAudio(ctx, domainSend.AudioRequest{
- BaseRequest: domainSend.BaseRequest{
- Phone: phone,
- IsForwarded: request.GetBool("is_forwarded", false),
- },
- AudioURL: &audioURL,
- PTT: request.GetBool("ptt", false),
- })
- if err != nil {
- return nil, err
- }
-
- return mcp.NewToolResultText(fmt.Sprintf("Audio sent successfully with ID %s", res.MessageID)), nil
-}
-
-func (s *SendHandler) toolSendPoll() mcp.Tool {
- return mcp.NewTool("whatsapp_send_poll",
- mcp.WithDescription("Send a poll to a WhatsApp contact or group. Requires at least 2 options."),
- mcp.WithTitleAnnotation("Send Poll"),
- mcp.WithReadOnlyHintAnnotation(false),
- mcp.WithDestructiveHintAnnotation(false),
- mcp.WithIdempotentHintAnnotation(false),
- mcp.WithString("phone",
- mcp.Required(),
- mcp.Description("Phone number or group ID to send the poll to"),
- ),
- mcp.WithString("question",
- mcp.Required(),
- mcp.Description("The poll question"),
- ),
- mcp.WithArray("options",
- mcp.Required(),
- mcp.Description("List of poll option strings (min 2). Example: [\"Option A\", \"Option B\", \"Option C\"]"),
- ),
- mcp.WithNumber("max_answer",
- mcp.Description("Maximum number of options a recipient can select (default: 1 for single-choice)"),
- ),
- )
-}
-
-func (s *SendHandler) handleSendPoll(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
- ctx, err := mcpHelpers.ContextWithDefaultDevice(ctx)
- if err != nil {
- return nil, err
- }
-
- phone, err := request.RequireString("phone")
- if err != nil {
- return nil, err
- }
-
- question, err := request.RequireString("question")
- if err != nil {
- return nil, err
- }
-
- // RequireStringSlice rejects non-string entries with an indexed error
- // instead of silently dropping them.
- options, err := request.RequireStringSlice("options")
- if err != nil {
- return nil, err
- }
- if len(options) < 2 {
- return nil, errors.New("options must contain at least 2 items")
- }
-
- res, err := s.sendService.SendPoll(ctx, domainSend.PollRequest{
- BaseRequest: domainSend.BaseRequest{
- Phone: phone,
- },
- Question: question,
- Options: options,
- MaxAnswer: request.GetInt("max_answer", 1),
- })
- if err != nil {
- return nil, err
- }
-
- return mcp.NewToolResultText(fmt.Sprintf("Poll sent successfully with ID %s", res.MessageID)), nil
-}
-
-func (s *SendHandler) toolForwardMessage() mcp.Tool {
- return mcp.NewTool("whatsapp_forward_message",
- mcp.WithDescription("Forward an existing stored message to another chat by message ID. Reuses media references when possible."),
- mcp.WithTitleAnnotation("Forward Message"),
- mcp.WithReadOnlyHintAnnotation(false),
- mcp.WithDestructiveHintAnnotation(false),
- mcp.WithIdempotentHintAnnotation(false),
- mcp.WithString("message_id",
- mcp.Required(),
- mcp.Description("Source message ID from chat storage"),
- ),
- mcp.WithString("phone",
- mcp.Required(),
- mcp.Description("Destination phone number or group JID"),
- ),
- mcp.WithNumber("duration",
- mcp.Description("Optional disappearing message duration in seconds (0, 86400, 604800, 7776000)"),
- ),
- mcp.WithBoolean("force_reupload",
- mcp.Description("Skip media reference reuse and re-upload media before sending (default: false)"),
- ),
- )
-}
-
-func (s *SendHandler) handleForwardMessage(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
- ctx, err := mcpHelpers.ContextWithDefaultDevice(ctx)
- if err != nil {
- return nil, err
- }
-
- messageID, err := request.RequireString("message_id")
- if err != nil {
- return nil, err
- }
-
- phone, err := request.RequireString("phone")
- if err != nil {
- return nil, err
- }
-
- forwardRequest := domainSend.ForwardRequest{
- MessageID: messageID,
- Phone: phone,
- ForceReupload: request.GetBool("force_reupload", false),
- }
-
- if args := request.GetArguments(); args != nil {
- if _, ok := args["duration"]; ok {
- duration, err := request.RequireInt("duration")
- if err != nil {
- return nil, err
+ return mcpg.NewToolResultError(err.Error()), nil
+ }
+
+ base := domainSend.BaseRequest{
+ Phone: phone,
+ IsForwarded: request.GetBool("is_forwarded", false),
+ }
+
+ var res domainSend.GenericResponse
+ switch msgType {
+ case "text":
+ replyID := request.GetString("reply_message_id", "")
+ res, err = s.sendService.SendText(ctx, domainSend.MessageRequest{
+ BaseRequest: base,
+ Message: request.GetString("message", ""),
+ ReplyMessageID: &replyID,
+ Mentions: request.GetStringSlice("mentions", nil),
+ })
+ case "image":
+ imageURL := request.GetString("image_url", "")
+ res, err = s.sendService.SendImage(ctx, domainSend.ImageRequest{
+ BaseRequest: base,
+ ImageURL: &imageURL,
+ Caption: request.GetString("caption", ""),
+ ViewOnce: request.GetBool("view_once", false),
+ Compress: request.GetBool("compress", true),
+ })
+ case "video":
+ videoURL := request.GetString("video_url", "")
+ res, err = s.sendService.SendVideo(ctx, domainSend.VideoRequest{
+ BaseRequest: base,
+ VideoURL: &videoURL,
+ Caption: request.GetString("caption", ""),
+ ViewOnce: request.GetBool("view_once", false),
+ GifPlayback: request.GetBool("gif_playback", false),
+ Compress: request.GetBool("compress", false),
+ })
+ case "audio":
+ audioURL := request.GetString("audio_url", "")
+ res, err = s.sendService.SendAudio(ctx, domainSend.AudioRequest{
+ BaseRequest: base,
+ AudioURL: &audioURL,
+ PTT: request.GetBool("ptt", false),
+ })
+ case "document":
+ fileURL := request.GetString("file_url", "")
+ res, err = s.sendService.SendFile(ctx, domainSend.FileRequest{
+ BaseRequest: base,
+ FileURL: &fileURL,
+ Caption: request.GetString("caption", ""),
+ })
+ case "sticker":
+ stickerURL := request.GetString("sticker_url", "")
+ res, err = s.sendService.SendSticker(ctx, domainSend.StickerRequest{
+ BaseRequest: base,
+ StickerURL: &stickerURL,
+ })
+ case "location":
+ res, err = s.sendService.SendLocation(ctx, domainSend.LocationRequest{
+ BaseRequest: base,
+ Latitude: request.GetString("latitude", ""),
+ Longitude: request.GetString("longitude", ""),
+ })
+ case "contact":
+ res, err = s.sendService.SendContact(ctx, domainSend.ContactRequest{
+ BaseRequest: base,
+ ContactName: request.GetString("contact_name", ""),
+ ContactPhone: request.GetString("contact_phone", ""),
+ })
+ case "poll":
+ res, err = s.sendService.SendPoll(ctx, domainSend.PollRequest{
+ BaseRequest: base,
+ Question: request.GetString("question", ""),
+ Options: request.GetStringSlice("options", nil),
+ MaxAnswer: request.GetInt("max_answer", 1),
+ })
+ case "link":
+ res, err = s.sendService.SendLink(ctx, domainSend.LinkRequest{
+ BaseRequest: base,
+ Link: request.GetString("link", ""),
+ Caption: request.GetString("caption", ""),
+ })
+ case "forward":
+ forwardReq := domainSend.ForwardRequest{
+ MessageID: request.GetString("message_id", ""),
+ Phone: phone,
+ ForceReupload: request.GetBool("force_reupload", false),
+ }
+ if args := request.GetArguments(); args != nil {
+ if _, ok := args["duration"]; ok {
+ duration := request.GetInt("duration", 0)
+ forwardReq.Duration = &duration
}
- forwardRequest.Duration = &duration
}
+ res, err = s.sendService.SendForward(ctx, forwardReq)
+ default:
+ return mcpg.NewToolResultError(fmt.Sprintf("unknown send type: %s", msgType)), nil
}
- res, err := s.sendService.SendForward(ctx, forwardRequest)
if err != nil {
- return nil, err
+ return mcpg.NewToolResultError(err.Error()), nil
}
-
- return mcp.NewToolResultText(fmt.Sprintf("Message forwarded successfully with ID %s", res.MessageID)), nil
+ return mcpg.NewToolResultText(fmt.Sprintf("%s sent successfully with ID %s", msgType, res.MessageID)), nil
}
diff --git a/src/ui/mcp/send_test.go b/src/ui/mcp/send_test.go
new file mode 100644
index 00000000..693a7d7a
--- /dev/null
+++ b/src/ui/mcp/send_test.go
@@ -0,0 +1,242 @@
+package mcp
+
+import (
+ "context"
+ "errors"
+ "testing"
+
+ domainSend "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/send"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+// stubSendService embeds the interface so only overridden methods matter;
+// an unexpected call panics, which is the failure we want in a dispatch test.
+type stubSendService struct {
+ domainSend.ISendUsecase
+ lastText *domainSend.MessageRequest
+ lastImage *domainSend.ImageRequest
+ lastVideo *domainSend.VideoRequest
+ lastAudio *domainSend.AudioRequest
+ lastFile *domainSend.FileRequest
+ lastSticker *domainSend.StickerRequest
+ lastLocation *domainSend.LocationRequest
+ lastContact *domainSend.ContactRequest
+ lastPoll *domainSend.PollRequest
+ lastLink *domainSend.LinkRequest
+ lastForward *domainSend.ForwardRequest
+ err error
+}
+
+func (s *stubSendService) resp() (domainSend.GenericResponse, error) {
+ if s.err != nil {
+ return domainSend.GenericResponse{}, s.err
+ }
+ return domainSend.GenericResponse{MessageID: "MSG1"}, nil
+}
+
+func (s *stubSendService) SendText(_ context.Context, r domainSend.MessageRequest) (domainSend.GenericResponse, error) {
+ s.lastText = &r
+ return s.resp()
+}
+func (s *stubSendService) SendImage(_ context.Context, r domainSend.ImageRequest) (domainSend.GenericResponse, error) {
+ s.lastImage = &r
+ return s.resp()
+}
+func (s *stubSendService) SendVideo(_ context.Context, r domainSend.VideoRequest) (domainSend.GenericResponse, error) {
+ s.lastVideo = &r
+ return s.resp()
+}
+func (s *stubSendService) SendAudio(_ context.Context, r domainSend.AudioRequest) (domainSend.GenericResponse, error) {
+ s.lastAudio = &r
+ return s.resp()
+}
+func (s *stubSendService) SendFile(_ context.Context, r domainSend.FileRequest) (domainSend.GenericResponse, error) {
+ s.lastFile = &r
+ return s.resp()
+}
+func (s *stubSendService) SendSticker(_ context.Context, r domainSend.StickerRequest) (domainSend.GenericResponse, error) {
+ s.lastSticker = &r
+ return s.resp()
+}
+func (s *stubSendService) SendLocation(_ context.Context, r domainSend.LocationRequest) (domainSend.GenericResponse, error) {
+ s.lastLocation = &r
+ return s.resp()
+}
+func (s *stubSendService) SendContact(_ context.Context, r domainSend.ContactRequest) (domainSend.GenericResponse, error) {
+ s.lastContact = &r
+ return s.resp()
+}
+func (s *stubSendService) SendPoll(_ context.Context, r domainSend.PollRequest) (domainSend.GenericResponse, error) {
+ s.lastPoll = &r
+ return s.resp()
+}
+func (s *stubSendService) SendLink(_ context.Context, r domainSend.LinkRequest) (domainSend.GenericResponse, error) {
+ s.lastLink = &r
+ return s.resp()
+}
+func (s *stubSendService) SendForward(_ context.Context, r domainSend.ForwardRequest) (domainSend.GenericResponse, error) {
+ s.lastForward = &r
+ return s.resp()
+}
+
+// deviceCtx returns a context that already carries a device, as the HTTP
+// layer would after resolving X-Device-Id.
+func deviceCtx() context.Context {
+ return whatsapp.ContextWithDevice(context.Background(), &whatsapp.DeviceInstance{})
+}
+
+func TestHandleSendDispatch(t *testing.T) {
+ t.Run("text", func(t *testing.T) {
+ svc := &stubSendService{}
+ h := InitMcpSend(svc, &stubResolver{})
+ res, err := h.handleSend(deviceCtx(), callReq(map[string]any{
+ "type": "text", "phone": "628", "message": "hi",
+ "reply_message_id": "R1", "mentions": []any{"629"}, "is_forwarded": true,
+ }))
+ require.NoError(t, err)
+ require.NotNil(t, res)
+ assert.False(t, res.IsError)
+ require.NotNil(t, svc.lastText)
+ assert.Equal(t, "628", svc.lastText.Phone)
+ assert.Equal(t, "hi", svc.lastText.Message)
+ assert.Equal(t, "R1", *svc.lastText.ReplyMessageID)
+ assert.Equal(t, []string{"629"}, svc.lastText.Mentions)
+ assert.True(t, svc.lastText.IsForwarded)
+ })
+
+ t.Run("image", func(t *testing.T) {
+ svc := &stubSendService{}
+ h := InitMcpSend(svc, &stubResolver{})
+ _, err := h.handleSend(deviceCtx(), callReq(map[string]any{
+ "type": "image", "phone": "628", "image_url": "http://x/a.png",
+ "caption": "c", "view_once": true,
+ }))
+ require.NoError(t, err)
+ require.NotNil(t, svc.lastImage)
+ assert.Equal(t, "http://x/a.png", *svc.lastImage.ImageURL)
+ assert.True(t, svc.lastImage.ViewOnce)
+ assert.True(t, svc.lastImage.Compress) // image compress defaults true
+ })
+
+ t.Run("video", func(t *testing.T) {
+ svc := &stubSendService{}
+ h := InitMcpSend(svc, &stubResolver{})
+ _, err := h.handleSend(deviceCtx(), callReq(map[string]any{
+ "type": "video", "phone": "628", "video_url": "http://x/a.mp4", "gif_playback": true,
+ }))
+ require.NoError(t, err)
+ require.NotNil(t, svc.lastVideo)
+ assert.True(t, svc.lastVideo.GifPlayback)
+ assert.False(t, svc.lastVideo.Compress) // video compress defaults false
+ })
+
+ t.Run("audio", func(t *testing.T) {
+ svc := &stubSendService{}
+ h := InitMcpSend(svc, &stubResolver{})
+ _, err := h.handleSend(deviceCtx(), callReq(map[string]any{
+ "type": "audio", "phone": "628", "audio_url": "http://x/a.ogg", "ptt": true,
+ }))
+ require.NoError(t, err)
+ require.NotNil(t, svc.lastAudio)
+ assert.True(t, svc.lastAudio.PTT)
+ })
+
+ t.Run("document", func(t *testing.T) {
+ svc := &stubSendService{}
+ h := InitMcpSend(svc, &stubResolver{})
+ _, err := h.handleSend(deviceCtx(), callReq(map[string]any{
+ "type": "document", "phone": "628", "file_url": "http://x/a.pdf",
+ }))
+ require.NoError(t, err)
+ require.NotNil(t, svc.lastFile)
+ })
+
+ t.Run("sticker", func(t *testing.T) {
+ svc := &stubSendService{}
+ h := InitMcpSend(svc, &stubResolver{})
+ _, err := h.handleSend(deviceCtx(), callReq(map[string]any{
+ "type": "sticker", "phone": "628", "sticker_url": "http://x/a.png",
+ }))
+ require.NoError(t, err)
+ require.NotNil(t, svc.lastSticker)
+ })
+
+ t.Run("location", func(t *testing.T) {
+ svc := &stubSendService{}
+ h := InitMcpSend(svc, &stubResolver{})
+ _, err := h.handleSend(deviceCtx(), callReq(map[string]any{
+ "type": "location", "phone": "628", "latitude": "-6.2", "longitude": "106.8",
+ }))
+ require.NoError(t, err)
+ require.NotNil(t, svc.lastLocation)
+ })
+
+ t.Run("contact", func(t *testing.T) {
+ svc := &stubSendService{}
+ h := InitMcpSend(svc, &stubResolver{})
+ _, err := h.handleSend(deviceCtx(), callReq(map[string]any{
+ "type": "contact", "phone": "628", "contact_name": "A", "contact_phone": "629",
+ }))
+ require.NoError(t, err)
+ require.NotNil(t, svc.lastContact)
+ })
+
+ t.Run("poll", func(t *testing.T) {
+ svc := &stubSendService{}
+ h := InitMcpSend(svc, &stubResolver{})
+ _, err := h.handleSend(deviceCtx(), callReq(map[string]any{
+ "type": "poll", "phone": "628", "question": "q", "options": []any{"a", "b"},
+ "max_answer": 2, "is_forwarded": true,
+ }))
+ require.NoError(t, err)
+ require.NotNil(t, svc.lastPoll)
+ assert.Equal(t, 2, svc.lastPoll.MaxAnswer)
+ assert.Equal(t, "628", svc.lastPoll.Phone)
+ assert.True(t, svc.lastPoll.IsForwarded)
+ })
+
+ t.Run("link", func(t *testing.T) {
+ svc := &stubSendService{}
+ h := InitMcpSend(svc, &stubResolver{})
+ _, err := h.handleSend(deviceCtx(), callReq(map[string]any{
+ "type": "link", "phone": "628", "link": "http://x", "caption": "c",
+ }))
+ require.NoError(t, err)
+ require.NotNil(t, svc.lastLink)
+ })
+
+ t.Run("forward with duration", func(t *testing.T) {
+ svc := &stubSendService{}
+ h := InitMcpSend(svc, &stubResolver{})
+ _, err := h.handleSend(deviceCtx(), callReq(map[string]any{
+ "type": "forward", "phone": "628", "message_id": "M1", "duration": 86400,
+ }))
+ require.NoError(t, err)
+ require.NotNil(t, svc.lastForward)
+ require.NotNil(t, svc.lastForward.Duration)
+ assert.Equal(t, 86400, *svc.lastForward.Duration)
+ })
+
+ t.Run("usecase error becomes tool error", func(t *testing.T) {
+ svc := &stubSendService{err: errors.New("boom")}
+ h := InitMcpSend(svc, &stubResolver{})
+ res, err := h.handleSend(deviceCtx(), callReq(map[string]any{
+ "type": "text", "phone": "628", "message": "hi",
+ }))
+ require.NoError(t, err)
+ require.NotNil(t, res)
+ assert.True(t, res.IsError)
+ })
+
+ t.Run("no device is a tool error", func(t *testing.T) {
+ svc := &stubSendService{}
+ h := InitMcpSend(svc, &stubResolver{})
+ res, err := h.handleSend(context.Background(), callReq(map[string]any{
+ "type": "text", "phone": "628", "message": "hi",
+ }))
+ require.NoError(t, err)
+ assert.True(t, res.IsError)
+ })
+}
diff --git a/src/ui/mcp/server.go b/src/ui/mcp/server.go
new file mode 100644
index 00000000..28f66a7d
--- /dev/null
+++ b/src/ui/mcp/server.go
@@ -0,0 +1,42 @@
+package mcp
+
+import (
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+ domainApp "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/app"
+ domainChat "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chat"
+ domainGroup "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/group"
+ domainMessage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/message"
+ domainSend "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/send"
+ domainUser "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/user"
+ "github.com/mark3labs/mcp-go/server"
+)
+
+// Deps carries the usecase instances the MCP tools call — the same instances
+// the REST handlers hold, so both surfaces share one whatsmeow session.
+type Deps struct {
+ App domainApp.IAppUsecase
+ Send domainSend.ISendUsecase
+ Chat domainChat.IChatUsecase
+ User domainUser.IUserUsecase
+ Message domainMessage.IMessageUsecase
+ Group domainGroup.IGroupUsecase
+}
+
+// NewServer builds the MCPServer with the 5 consolidated tools registered.
+func NewServer(deps Deps, resolver deviceResolver) *server.MCPServer {
+ s := server.NewMCPServer(
+ "WhatsApp Web Multidevice MCP Server",
+ config.AppVersion,
+ server.WithToolCapabilities(true),
+ // Enforce the schemas' allOf/if/then conditionals at the mcp-go
+ // layer, before any handler runs (SEP-1303). Without this,
+ // inputValidator stays nil and the conditionals are advisory only.
+ server.WithInputSchemaValidation(),
+ )
+ InitMcpSend(deps.Send, resolver).AddSendTools(s)
+ InitMcpMessage(deps.Message, resolver).AddMessageTools(s)
+ InitMcpChat(deps.Chat, deps.User, resolver).AddChatTools(s)
+ InitMcpGroup(deps.Group, resolver).AddGroupTools(s)
+ InitMcpApp(deps.App, resolver).AddAppTools(s)
+ return s
+}
diff --git a/src/validations/message_validation.go b/src/validations/message_validation.go
index 057f121b..20ec5a29 100644
--- a/src/validations/message_validation.go
+++ b/src/validations/message_validation.go
@@ -80,7 +80,7 @@ func ValidateStarMessage(ctx context.Context, request domainMessage.StarRequest)
err := validation.ValidateStructWithContext(ctx, &request,
validation.Field(&request.Phone, validation.Required),
validation.Field(&request.MessageID, validation.Required),
- validation.Field(&request.IsStarred, validation.Required),
+ validation.Field(&request.IsStarred),
)
if err != nil {
diff --git a/src/validations/message_validation_test.go b/src/validations/message_validation_test.go
index cf590b3e..450c5661 100644
--- a/src/validations/message_validation_test.go
+++ b/src/validations/message_validation_test.go
@@ -241,8 +241,7 @@ func TestValidateStarMessage(t *testing.T) {
MessageID: "3EB0789ABC123456",
IsStarred: false,
}},
- // Note: validation.Required treats false as blank for boolean fields
- err: pkgError.ValidationError("is_starred: cannot be blank."),
+ err: nil,
},
{
name: "should error with empty phone",
@@ -269,8 +268,7 @@ func TestValidateStarMessage(t *testing.T) {
MessageID: "",
IsStarred: false,
}},
- // All three fields will fail validation when IsStarred is false
- err: pkgError.ValidationError("is_starred: cannot be blank; message_id: cannot be blank; phone: cannot be blank."),
+ err: pkgError.ValidationError("message_id: cannot be blank; phone: cannot be blank."),
},
}
@@ -279,11 +277,6 @@ func TestValidateStarMessage(t *testing.T) {
err := ValidateStarMessage(context.Background(), tt.args.request)
if tt.err == nil {
assert.NoError(t, err)
- } else if tt.name == "should error with empty phone and message id" {
- assert.Error(t, err)
- assert.Contains(t, err.Error(), "is_starred: cannot be blank")
- assert.Contains(t, err.Error(), "message_id: cannot be blank")
- assert.Contains(t, err.Error(), "phone: cannot be blank")
} else {
assert.Equal(t, tt.err, err)
}