Production-grade, modular automation service and CLI for interacting with Mattermost using your personal identity.
Why This Exists β’ Architecture β’ Features β’ Quick Start β’ Channel Mapping β’ CLI Reference β’ Web UI & API Gateway β’ Cron Jobs β’ MCP Server (AI Agents) β’ TypeScript SDK β’ Security β’ Testing
Most Mattermost automation tools rely on Incoming Webhooks, Bot Accounts, or Personal Access Tokens (PAT). In corporate and enterprise environments, this presents major blockers:
- Permission Friction (Not Everyone is an Admin): Regular team members cannot generate Personal Access Tokens or create webhooks arbitrarily because workspace policies restrict these to administrators.
- Identity Attribution: Messages sent via bot accounts or incoming webhooks look like impersonal bots, stripping away personal responsibility and developer context (e.g. who made the PR or deployed the fix).
- SSO & MFA Obstacles: Corporate instances often require Google Workspace / Okta / SAML login with MFA, which standard script-based HTTP bots cannot bypass without administrative API tokens.
Mattermost Personal Account Automation solves this by prioritizing a Zero-Admin Browser Automation Layer (Playwright) as the primary default strategy, with direct API support as a fast alternative:
- π Strategy 1 β Persistent Browser Context (Playwright β Primary & Default):
- Zero admin privileges required.
- Works for any corporate user with a standard Mattermost account.
- Full support for SSO (Google, Okta, GitLab, SAML) and Multi-Factor Authentication (MFA).
- You log in manually once via
npm run cli -- login. The session is securely saved locally and reused headless.
- β‘ Strategy 2 β REST API v4 (Personal Access Tokens β Optional Alternative):
- For power users or environments where Personal Access Tokens are explicitly permitted.
The system enforces strict separation of concerns across Domain, Infrastructure, Application, and Client layers:
flowchart TD
subgraph TriggerLayer ["Client & Trigger Layer"]
CLI["CLI Command (mattermost send / whoami / sync)"]
Agent["AI Agent / CI Hook / Unix Pipe (JSON Action)"]
CodeSDK["Node.js / TypeScript Application"]
end
subgraph AppLayer ["Application Layer"]
Service["MattermostAutomationService"]
Actions["Domain Actions (send_message, reply_to_message, read_channel, get_channel, whoami)"]
Validator["Zod Action Validator"]
Resolver["ChannelResolver (YAML Aliases & TTL Cache)"]
SyncService["ChannelSyncService (Auto-Discovery)"]
Idempotency["IdempotencyManager (In-Flight Promise Sharing)"]
end
subgraph DomainLayer ["Domain Layer"]
ProviderInterface["interface MattermostProvider"]
Entities["Entities (User, Channel, Post, Team)"]
Errors["Typed Error Hierarchy (AuthError, DisabledError, NotFoundError)"]
end
subgraph InfraLayer ["Infrastructure Layer"]
PlaywrightProvider["MattermostPlaywrightProvider (Primary: Persistent Session)"]
ApiProvider["MattermostApiProvider (Alternative: REST API v4)"]
PageObjects["Page Objects (MattermostComposer, MattermostChannelPage)"]
Logger["Structured Logger (Automated Secret Sanitization)"]
end
CLI --> Service
Agent --> Service
CodeSDK --> Service
Service --> Validator
Validator --> Actions
Actions --> Resolver
Actions --> Idempotency
Service --> SyncService
Actions --> ProviderInterface
ProviderInterface -.-> PlaywrightProvider
ProviderInterface -.-> ApiProvider
PlaywrightProvider --> PageObjects
ApiProvider --> Logger
PlaywrightProvider --> Logger
| Feature | Description |
|---|---|
| Zero-Admin Setup | Uses persistent Playwright session by default so standard non-admin users can automate without tokens or webhook creation. |
| Personal Account Attribution | All posts, replies, and channel operations appear authentically as your personal Mattermost user. |
| Auto Channel Discovery | Auto-discovers all channels across teams on login and generates channels.yml with enabled: true/false toggles. |
| Dual Provider Support | Primary Playwright provider + optional high-speed REST API v4 provider via configuration switch. |
| Smart Channel Resolution | Accepts channel names (engineering), YAML aliases (backend-dev), slugs (~engineering), or 26-char IDs. |
| Idempotency & Deduplication | In-flight execution lock and cached response store prevents duplicate messages during retry storms. |
| Identity Verification Lock | Startup self-check verifies identity against MATTERMOST_EXPECTED_USER_ID, preventing unintended execution. |
| Zero Credential Leaks | Automated regex scrubbing masks Bearer tokens, cookies, passwords, and session data in logs, errors, and CLI outputs. |
| AI Agent / CLI Integration | Native JSON action interface supporting standard Unix pipes (echo '{...}' | mattermost action). |
- Node.js:
v18.0.0or higher - npm, pnpm, or bun
git clone https://github.com/egagofur/Mattermost-Agent.git
cd Mattermost-Agent
npm installCopy .env.example to .env:
cp .env.example .envSet your Mattermost server URL:
MATTERMOST_URL=https://mattermost.example.com
MATTERMOST_PROVIDER=playwrightAuthenticate once using the interactive login helper:
npm run cli -- loginA browser window will open. Complete your standard login (including Google/Okta SSO or MFA). Once completed, the session is saved to data/mattermost-browser/ and all your accessible channels are automatically synced to channels.yml!
Recommended for all users (no administrator privileges needed):
- Keep
MATTERMOST_PROVIDER=playwrightin.env. - Run:
npm run cli -- login
- Complete your login in the browser window.
- From then on, all commands (
send,read,sync, etc.) run headlessly in the background using your authenticated profile.
For users whose Mattermost installation permits generating Personal Access Tokens:
- Set
MATTERMOST_PROVIDER=apiin.env. - Generate a token under Settings
$\rightarrow$ Security$\rightarrow$ Personal Access Tokens. - Set
MATTERMOST_TOKEN=<your_token>in.env.
Instead of configuring channels one-by-one, use Auto-Discovery to fetch all accessible channels across all your teams and generate channels.yml with toggles!
Run the sync command:
npm run cli -- syncOutput:
π Discovering all accessible channels from Mattermost...
β
Channels Synchronized Successfully!
File: channels.yml
Discovered: 24 channels across 3 team(s)
Status: 24 enabled, 0 disabled
-------------------------------------------------------------
π’ [ENABLED] town-square β #town-square (team: engineering-team)
π’ [ENABLED] engineering β #engineering (team: engineering-team)
π’ [ENABLED] backend-dev β #dotify-backend-dev (team: dot-dev)
π’ [ENABLED] qa-alerts β #automated-qa-reports (team: quality-assurance)
-------------------------------------------------------------
π‘ You can now easily toggle 'enabled: true/false' in 'channels.yml'.
Simply toggle enabled: false for channels you do not wish automation to post to:
default_team: engineering-team
fallback_channel: town-square
channels:
engineering:
channel: engineering
team: engineering-team
enabled: true
description: "Main team channel"
backend-dev:
channel: dotify-backend-dev
team: dot-dev
enabled: true
# Disabled channel (safe from accidental automation posts)
secret-project:
channel: secret-project
team: confidential-team
enabled: false
# Environment overlays (activated via MATTERMOST_ENV or --env)
environments:
prod:
backend-dev:
channel: dotify-backend-prod
team: dot-prodNote
Re-running mattermost sync will automatically discover new channels while preserving your existing enabled: false toggles and custom descriptions.
npm run cli -- aliasesRun via npm run <script> -- <args> or npm run cli -- <command>:
Usage: mattermost [options] [command]
Commands:
whoami Verify personal identity and display current account
send [channel] [message] Send a message (e.g. `send per-fe-an "Hello"`)
reply [channel] [rootId] [message] Reply to a thread (supports :1, :latest, --find, permalink)
edit <postIdOrPermalink> <msg> Edit an existing message
react <postIdOrPermalink> <emoji> Add an emoji reaction to a post
thread <permalinkOrId> View complete sequential messages in a thread
post <postIdOrPermalink> View a post with surrounding context in the channel
mentions List recent posts mentioning your account
search [terms] Search messages across channels with filters
unread Summarize unread channels and mentions
user <usernameOrId> Look up user profile, roles, and position
file <fileId> Download an attachment file safely
threads [channel] [query] List & search active threads in a channel
channels [query] List & search configured channels in channels.yml
enable <channel> Enable a channel in channels.yml
disable <channel> Disable a channel in channels.yml
read [channel] Read recent messages from a channel
sync Auto-discover all accessible channels from server
login Open browser window for manual login (Playwright)
action [jsonPayload] Execute a domain action via JSON or stdin
Finding thread IDs is now effortless. You no longer need to copy random 26-character hashes!
npm run threads -- per-fe-anπ§΅ Active Threads in #per-fe-an (11 threads):
-----------------------------------------------------------------------------------------
[1] pyo47np3djgqjdpgq8xrrmdwiw β’ 8m ago β’ (0 replies)
"Testing user-friendly positional syntax!"
[2] 31ewigbaoigepj5qsh3xb9bbjo β’ 15m ago β’ (2 replies)
"Testing from Mettermost Agent"
β³ Last reply (10m ago): "Ini balasan di thread"
-----------------------------------------------------------------------------------------
# Reply to the most recent thread in the channel:
npm run reply -- per-fe-an :1 "Approved and ready to merge!"
npm run reply -- per-fe-an :latest "Approved and ready to merge!"# Finds the thread mentioning "Standup" and replies there automatically:
npm run reply -- per-fe-an --find "Standup" "Hadir, update task hari ini aman"npm run reply -- "https://mattermost.example.com/core/pl/31ewigbaoigepj5qsh3xb9bbjo" "Looks good to me!"npm run send -- per-fe-an "Deployment started..."
npm run reply -- per-fe-an --last "Deployment completed successfully! β
"To maintain transparency and ensure team members know whether a message was sent manually by the person or by an AI / CI tool, use the from property:
# Add custom attribution footer:
npm run send -- per-fe-an "MR !123 is ready for review." --from "AI"
npm run send -- per-fe-an "Pipeline #45 passed" --from "GitLab CI"Rendered message in Mattermost:
MR !123 is ready for review.
*~ from AI*
- Set Default via
.env:MATTERMOST_DEFAULT_FROM=AI - Suppress attribution: Pass
--no-fromin CLI. - JSON Action / AI Agent:
{ "action": "send_message", "channel": "per-fe-an", "message": "PR is ready for review.", "from": "AI Agent" }
npm run cli -- read engineering --limit 5echo '{"action":"send_message","channel":"engineering","message":"Automated deployment completed."}' | npm run cli -- actionJSON Response:
{
"success": true,
"data": {
"id": "post_123456789",
"channelId": "chan_engineering_id",
"userId": "usr_egagofur",
"message": "Automated deployment completed.",
"createdAt": "2026-08-24T10:45:00.000Z"
}
}mattermost-agent includes a high-density, interactive Web Dashboard and REST API Gateway for direct developer integrations.
# Launch the Web Dashboard & API Gateway on port 3000:
npm run ui
# Or via CLI:
mattermost ui --port 3000Open http://localhost:3000 in your browser to access the dashboard!
- 1-Click Auto Login: Trigger interactive Playwright browser login directly from the web UI with live progress indicators.
- Channel & Thread Explorer: Visual thread tree viewer with
:1,:2shortcuts and quick reply box. - Cron Job Manager: Visual schedule overview with next run countdowns, 1-click manual execution, and enable/disable switches.
- Interactive API Playground: Live sandbox with multi-language code snippets (cURL, TypeScript / Node.js, Python, Go, PHP) and real-time response viewer.
- Live Activity Console: Real-time Server-Sent Events (SSE) stream for message events, auth state, and cron executions.
| Method | Endpoint | Description |
|---|---|---|
GET |
/api/status |
Get session connection & authenticated user state |
POST |
/api/auth/login |
Trigger 1-Click interactive browser login |
GET |
/api/channels |
List configured channels, aliases, and enabled flags |
POST |
/api/channels/sync |
Re-sync accessible channels across all teams |
POST |
/api/channels/toggle |
Enable or disable a channel dynamically |
GET |
/api/threads?channel=:c |
Get active channel threads with :1 shortcuts |
POST |
/api/messages/send |
Send a top-level message with attribution (from) |
POST |
/api/messages/reply |
Reply to thread via ID, :1 shortcut, or query |
GET |
/api/messages/history?channel=:c |
Read recent messages from a channel |
GET |
/api/cron |
List configured recurring cron jobs |
POST |
/api/cron/run |
Manually trigger a cron job execution |
POST |
/api/cron/toggle |
Enable or disable a cron job |
GET |
/api/openapi.json |
Download OpenAPI 3.0 specification |
curl -X POST http://localhost:3000/api/messages/send \
-H "Content-Type: application/json" \
-d '{
"channel": "town-square",
"message": "Hello from Mattermost Agent REST API!",
"from": "Webhook Agent"
}'mattermost-agent includes a declarative Cron Scheduler Engine for running recurring reminders, automated standup prompts, healthchecks, and periodic team syncs directly under your personal account.
Create a cron.yml file (template available at cron.example.yml):
default_timezone: Asia/Jakarta
jobs:
# Daily standup prompt every Mon-Fri at 09:00 WIB
daily-standup:
schedule: "0 9 * * 1-5"
channel: per-fe-an
message: "Selamat pagi rekan-rekan! Jangan lupa isi daily standup hari ini ya."
from: "Daily Reminder"
enabled: true
timezone: Asia/Jakarta
description: "Daily engineering standup prompt"
# Weekly demo sync reminder every Friday at 16:00 WIB
weekly-demo-reminder:
schedule: "0 16 * * 5"
channel: town-square
message: "Reminder: Demo sprint & weekly sync akan dimulai dalam 30 menit."
from: "Sprint Bot"
enabled: true
# Hourly healthcheck ping (disabled by default)
healthcheck:
schedule: "0 * * * *"
channel: devops
message: "Routine healthcheck ping."
enabled: false# List all configured jobs, schedules, and next calculated run times:
npm run cron:list
# Start the continuous scheduler daemon worker:
npm run cron:start
# Trigger an immediate single test run of a job:
npm run cli -- cron run daily-standup
# Enable or disable a job dynamically in cron.yml:
npm run cli -- cron enable healthcheck
npm run cli -- cron disable healthcheckmattermost-agent includes a built-in MCP Server over standard I/O (stdio), allowing AI coding assistants and agents (Cursor, Claude Desktop, Antigravity, Windsurf, Claude Code, etc.) to directly read and send Mattermost messages as your personal user!
{
"mcpServers": {
"mattermost": {
"command": "node",
"args": ["/ABSOLUTE/PATH/TO/mattermost-agent/dist/mcp/index.js"],
"env": {
"MATTERMOST_URL": "https://mattermost.example.com",
"MATTERMOST_PROVIDER": "playwright",
"MATTERMOST_DEFAULT_FROM": "AI Agent"
}
}
}
}- macOS:
~/Library/Application Support/Claude/claude_desktop_config.json - Windows:
%APPDATA%\Claude\claude_desktop_config.json
{
"mcpServers": {
"mattermost": {
"command": "node",
"args": ["/ABSOLUTE/PATH/TO/mattermost-agent/dist/mcp/index.js"]
}
}
}{
"mcpServers": {
"mattermost": {
"command": "node",
"args": ["/ABSOLUTE/PATH/TO/mattermost-agent/dist/mcp/index.js"]
}
}
}{
"mcpServers": {
"mattermost": {
"command": "node",
"args": ["/ABSOLUTE/PATH/TO/mattermost-agent/dist/mcp/index.js"]
}
}
}claude mcp add mattermost -- node /ABSOLUTE/PATH/TO/mattermost-agent/dist/mcp/index.jsAdd to your extension settings (cline_mcp_settings.json):
{
"mcpServers": {
"mattermost": {
"command": "node",
"args": ["/ABSOLUTE/PATH/TO/mattermost-agent/dist/mcp/index.js"],
"disabled": false,
"autoApprove": []
}
}
}| Tool Name | Type | Description |
|---|---|---|
mattermost_whoami |
Read | Verify authenticated identity (username, user ID, email, roles). |
mattermost_list_channels |
Read | List all discovered & configured channels with enabled status and aliases. |
mattermost_get_threads |
Read | List active threads in a channel with preview, reply counts, and :1 shortcuts. |
mattermost_get_thread |
Read | View full sequential messages in a thread from post ID or permalink URL. |
mattermost_get_mentions |
Read | List posts mentioning your account with reply statuses. |
mattermost_search |
Read | Search messages across channels with keywords, user, channel, and date filters. |
mattermost_unread_summary |
Read | Retrieve summary of all unread channels and mentions prioritized by mentions. |
mattermost_get_post |
Read | Retrieve a post along with surrounding contextual messages before and after. |
mattermost_get_user |
Read | Retrieve user profile details, roles, and position by username or ID. |
mattermost_get_file |
Read | Securely download an attachment file by file ID into local directory. |
mattermost_send_message |
Write | Send a message to a channel. Requires approved: true. |
mattermost_reply_thread |
Write | Reply to a thread via shortcut, keyword, or permalink. Requires approved: true. |
mattermost_edit_message |
Write | Edit an existing post/message. Requires approved: true. |
mattermost_add_reaction |
Write | Add an emoji reaction to a post. Requires approved: true. |
mattermost_read_channel |
Read | Read recent channel posts and thread replies. |
mattermost_sync_channels |
Read | Auto-discover all channels across teams and sync to channels.yml. |
mattermost_list_cron_jobs |
Read | List configured cron jobs, schedules, and next run calculations. |
mattermost_run_cron_job |
Action | Trigger an immediate test execution of a specific cron job. |
mattermost_toggle_cron_job |
Action | Enable or disable a cron job dynamically in cron.yml. |
To prevent AI coding assistants from unintentionally sending, editing, or reacting to messages without human review, all write operations at the MCP layer (mattermost_send_message, mattermost_reply_thread, mattermost_edit_message, and mattermost_add_reaction) enforce an explicit approval guard:
- When
approved: trueis omitted orfalse:- The tool does NOT call the server or send any message.
- Instead, it returns a safe
draft_previewJSON containing the payload details for the agent/user to review.
- When
approved: trueis explicitly provided:- The action is confirmed and dispatched to Mattermost.
Note
This safety guard applies strictly to the MCP Server layer for AI agents. CLI commands (mattermost send, reply, react) and automated cron jobs operate directly without requiring the approved flag.
Integrate Mattermost personal account automation directly into your Node.js/TypeScript services:
import { MattermostAutomationService, loadConfig } from 'mattermost-agent';
async function main() {
// 1. Initialize service with environment or custom config
const service = new MattermostAutomationService();
// 2. Startup identity check (optional fail-fast)
const me = await service.whoami();
console.log(`Authenticated as @${me.username} (${me.id})`);
// 3. Post a message to a channel (resolves name automatically)
const post = await service.sendMessage({
channel: 'engineering',
message: 'π CI Build #120 passed all integration tests.',
});
console.log(`Message sent: ${post.id}`);
// 4. Reply to the created thread
await service.replyToMessage({
channel: 'engineering',
rootId: post.id,
message: 'Artifacts available at: https://ci.example.com/build/120',
});
// 5. Read recent posts from a channel
const { channel, messages } = await service.readChannel({
channel: 'engineering',
limit: 10,
});
console.log(`Read ${messages.length} messages from #${channel.displayName}`);
// 6. Execute structured domain action (AI agent / webhook format)
const actionResult = await service.executeAction({
action: 'send_message',
channel: 'engineering',
message: 'Triggered from agent workflow.',
idempotencyKey: 'event-unique-id-9988',
});
if (actionResult.success) {
console.log('Action success:', actionResult.data);
} else {
console.error(`Action failed [${actionResult.error?.code}]: ${actionResult.error?.message}`);
}
// 7. Cleanup
await service.close();
}
main().catch(console.error);- Zero Secret Logging: Tokens, Bearer headers, session cookies, and passwords are automatically redacted by the logger and error formatting layer before output.
- No Password Storage: The system never asks for, stores, or automates password inputs.
- Session Isolation: Playwright browser profile files (
data/mattermost-browser/) and.envconfiguration files are explicitly ignored in.gitignore. - Idempotent Retries: Network retries are only performed for transient errors (e.g.
502,503,429, timeout) with exponential backoff and jitter, preventing duplicate post spam. - Identity Guard: Optional
MATTERMOST_EXPECTED_USER_IDorMATTERMOST_EXPECTED_USERNAMEprevents the automation from executing if the active credentials belong to an unexpected account.
The codebase includes a test suite covering configuration parsing, action schemas, channel resolution, idempotency locks, API client status mapping, and browser provider fallbacks.
# Run all unit and integration tests
npm test
# Run tests in watch mode
npm run test:watch
# Run TypeScript typecheck
npm run typecheck
# Build distribution bundle
npm run buildInstall the canonical SKILL.md and register the mattermost MCP server across all detected AI coding hosts (Antigravity / Gemini, Claude Code, OpenAI Codex, Cursor, OpenCode, Windsurf, and ~/.agents/skills) in one command:
npm run build
mattermost host sync
mattermost host doctorThe MCP server also exposes mattermost://skill as an MCP Resource so any MCP-capable host can load the skill instructions directly.
Manage separate workspaces (e.g. work, community) with isolated browser sessions in ~/.mattermost/profiles/<name>/:
mattermost profile add work --url https://mattermost.work.com --provider playwright
mattermost profile add community --url https://community.mattermost.com --token <PAT>
mattermost profile list
mattermost profile use work
mattermost send --profile community general "Hi all"Launch the interactive Terminal UI dashboard:
mattermost tui
# or: npm run tuiSend messages or replies with file/image attachments:
mattermost send engineering "Test report attached:" --file ./report.pdf --file ./screenshot.png --from "AI Agent"- GitLab CI/CD β Merge Request & release notifications
- GitHub Actions β Deployment alerts on workflow completion
- Docker & Docker Compose β Containerized Cron Scheduler daemon
- Git Hooks β Automated
post-commit/post-pushteam updates
Contributions, issues, and feature requests are welcome! Feel free to check the issues page.
- Fork the repository
- Create your feature branch (
git checkout -b feat/amazing-feature) - Commit your changes (
git commit -m 'feat: add amazing feature') - Push to the branch (
git push origin feat/amazing-feature) - Open a Pull Request
If this tool helped you or your team automate Mattermost without admin headache, please consider giving it a βοΈ on GitHub!
This project is licensed under the MIT License. Distributed as open source software to empower developers and engineering teams worldwide.