messaging-rules-mcp
by Pinlyx
README.md
# messaging-rules
**Can I message this person right now?** Source-cited rules for WhatsApp, Instagram, Messenger, Telegram and X, as data, a library and an MCP tool.
```ts
canMessage({ channel: 'instagram', lastInboundAt: '2026-11-19T09:00:00Z', sender: 'bot' })
// { allowed: false,
// reason: 'The 24h standard messaging window closed at 2026-11-20T09:00:00.000Z. After it: Only HUMAN_AGENT tagged replies sent by a person, ...',
// allowedAlternatives: [], sources: ['https://developers.facebook.com/...'] }
```
## Why
The rules that decide whether a business may message someone are spread across dozens of platform pages, change several times a year, and are mostly explained second-hand in vendor help centers, each covering a fragment. There is no machine-readable source, so developers and AI agents keep breaking them:
- sending free-form WhatsApp text after the 24-hour customer service window closed (only an approved template is allowed then);
- replying from an Instagram or Messenger bot with the `HUMAN_AGENT` tag (it is for a person replying manually, within 7 days);
- still using the Messenger `ACCOUNT_UPDATE`, `POST_PURCHASE_UPDATE` or `CONFIRMED_EVENT_UPDATE` tags, which return error 100 since 2026-04-27;
- trying to have a Telegram bot start a chat (a user has to message it first);
- sending a 1,500 character Instagram DM (the limit is 1,000 bytes) or a 6 MB WhatsApp image (5 MB).
This repository turns those rules into one JSON file per channel. Every value carries the official URL it was read from, a short quote from that page and the date it was verified. A TypeScript library, a Python port and an MCP server answer the two questions that matter before sending: *may I send this now?* and *will this message be accepted?*
<!-- summary:start -->
| Channel | Who messages first | Reply window | After the window | Text max | Attachments per message | Verified |
| --- | --- | --- | --- | --- | --- | --- |
| [WhatsApp](RULES.md#whatsapp) | Business may start: Template message | 24 hours | Only pre-approved template messages. | 4,096 characters | 1 | 2026-11-20 |
| [Instagram](RULES.md#instagram) | The person | 24 hours | Only HUMAN_AGENT tagged replies sent by a person, within 7 days of the user's last message. | 999 characters, 1,000 UTF-8 bytes | 10 | 2026-11-20 |
| [Messenger](RULES.md#messenger) | The person | 24 hours | A HUMAN_AGENT tagged reply by a person (7 days), an approved utility template, a marketing message to an opted-in person, or a sponsored message. | 2,000 characters | 30 | 2026-11-20 |
| [Telegram](RULES.md#telegram) | The person | Opens once, never expires | n/a | 4,096 characters | 10 | 2026-11-20 |
| [X](RULES.md#x) | Business may start: Direct Message | None | No window applies | no documented maximum | 1 | 2026-11-20 |
<!-- summary:end -->
Full tables with a source link on every value: **[RULES.md](RULES.md)**.
## Install
Not on npm or PyPI yet; install from GitHub.
```bash
# TypeScript / JavaScript (Node 18+): library and the messaging-rules-mcp command
npm install github:Pinlyx/messaging-rules
# Python 3.9+ (standard library only)
pip install "git+https://github.com/Pinlyx/messaging-rules#subdirectory=python"
```
## Quick start
### TypeScript
```ts
import { canMessage, validateMessage, getChannel } from 'messaging-rules';
// A WhatsApp user wrote 23 hours ago: free-form is still allowed.
const r = canMessage({
channel: 'whatsapp',
lastInboundAt: new Date(Date.now() - 23 * 3600_000),
sender: 'bot',
});
console.log(r.allowed, r.windowEndsAt); // true, about one hour from now
// 30 hours ago: only a template.
const late = canMessage({ channel: 'whatsapp', lastInboundAt: new Date(Date.now() - 30 * 3600_000) });
console.log(late.allowed, late.allowedAlternatives.map((a) => a.kind)); // false [ 'template' ]
// A person (not a bot) answering on Instagram 3 days later may use the HUMAN_AGENT tag.
canMessage({
channel: 'instagram',
lastInboundAt: new Date(Date.now() - 3 * 86400_000),
sender: 'human',
kind: 'tag',
tag: 'HUMAN_AGENT',
}).allowed; // true
// Check a draft before sending it.
validateMessage('whatsapp', {
caption: 'New menu',
attachments: [{ type: 'image', bytes: 6_000_000, mime: 'image/png' }],
});
// { ok: false, problems: [{ code: 'file_too_large', limit: 5000000, actual: 6000000, source: '...', ... }] }
getChannel('telegram')?.rate_limits; // per chat, per group, broadcast limits with sources
```
### Python
```python
from datetime import datetime, timedelta, timezone
from messaging_rules import can_message, validate_message, get_channel
now = datetime.now(timezone.utc)
r = can_message(channel="messenger", last_inbound_at=now - timedelta(hours=30), sender="bot")
print(r["allowed"]) # False
print([a["kind"] for a in r["allowed_alternatives"]])
# ['tag', 'utility_template', 'marketing_message', 'sponsored'] (the tag is NON_PROMOTIONAL_SUBSCRIPTION, news Pages only)
print(validate_message("telegram", text="x" * 5000)["problems"][0]["code"]) # text_too_long
print(get_channel("x")["limits"]["attachments_per_message"]["max"]) # 1
```
The Python functions take the same arguments in snake_case and return plain dicts with snake_case keys (`window_ends_at`, `allowed_alternatives`).
### MCP server
The npm package ships a stdio MCP server, `messaging-rules-mcp`, with three tools:
| Tool | What it answers |
| --- | --- |
| `check_messaging_window` | May this sender send this kind of message on this channel now? Returns `allowed`, `reason`, `windowEndsAt`, `conditions`, `allowedAlternatives`, `sources`. |
| `validate_message` | Does this draft fit the channel's text, caption, attachment, media size/type and button limits? |
| `get_channel_rules` | The full source-cited rules for a channel, one section of them, or a summary of all channels. |
Add it to any MCP client that supports stdio servers:
```json
{
"mcpServers": {
"messaging-rules": {
"command": "npx",
"args": ["-y", "github:Pinlyx/messaging-rules"]
}
}
}
```
If you installed the package, use `"command": "messaging-rules-mcp"` (or `node node_modules/messaging-rules/dist/mcp.js`) instead. The server reads only the bundled data: no network, no keys.
## API
### `canMessage(input)` / `can_message(**input)`
| Input | Meaning |
| --- | --- |
| `channel` | `whatsapp`, `instagram`, `messenger`, `telegram` or `x`. |
| `lastInboundAt` | When the person last messaged you: `Date`, ISO 8601 string (UTC when no offset is given) or epoch milliseconds. `null` if they never did. For `private_reply`, pass the time of the comment. |
| `now` | Defaults to the current time. |
| `sender` | `bot` (default) or `human`. |
| `kind` | `free_form` (default), `template` (WhatsApp), `tag`, `private_reply` (Instagram, Messenger), `utility_template`, `marketing_message`, `sponsored` (Messenger). |
| `tag` | With `kind: 'tag'`, for example `HUMAN_AGENT`. |
| `openedBy` | `ad_referral` when the conversation started from a click-to-message ad (Instagram and Messenger windows can then last up to 7 days). |
Returns `{ allowed, reason, channel, kind, tag?, windowEndsAt?, conditions, allowedAlternatives, sources }`. A window is open while `now < lastInboundAt + duration`, so exactly 24 hours later it is closed. `conditions` lists what the data cannot check for you (opt-in, permissions, recipient settings). `allowedAlternatives` lists other kinds or tags that would be allowed at the same moment.
### `validateMessage(channel, message)` / `validate_message(channel, ...)`
`message` may contain `text`, `caption`, `attachments` (`[{ type, bytes?, mime?, filename?, viaUrl? }]`), `buttons`, `quickReplies` and `listRows` (titles). Returns `{ ok, channel, problems }`; each problem has a `code`, `severity` (`error` or `warning`), `field`, `message` and, where relevant, `limit`, `actual` and `source`. `ok` is false only when there is an error.
Lengths are counted in UTF-16 code units, which is never less than the number of characters, so the check errs on the safe side (an emoji counts as 2). Instagram also has a byte limit, counted in UTF-8.
### Other exports
`getChannel(id)`, `listChannels()`, `CHANNEL_IDS` and all TypeScript types. The raw files are importable as `messaging-rules/channels/<id>.json` and `messaging-rules/schema/channel.schema.json`.
## Data format
`channels/<id>.json`, validated by [`schema/channel.schema.json`](schema/channel.schema.json):
| Field | Holds |
| --- | --- |
| `initiation` | Whether the person must message first, plus cited rules. |
| `windows` | `duration_hours` (`null` = never expires), `starts_on`, `resets_on`, `applies_to` (`bot`, `human`, `any`), optional `only_when_opened_by` and `max_messages`, and `after_window` (what is still allowed). |
| `message_kinds` | Which windows a kind needs, or `allowed_without_window` plus `conditions`; template `categories`. |
| `tags` | `status` (`active` or `retired` with `retired_on`), `applies_to`, own `window`, `requirements`. |
| `limits` | `text`, `caption`, `attachments_per_message`, `media` (type, MIME types or extensions, `max_bytes`, `max_size_documented`), `buttons`, `quick_replies`, `list_rows`, `other`. |
| `rate_limits` | `limit` per `period_seconds` and `scope`, or a `formula`. |
| `notes`, `sources` | Cited caveats, and every official page used. |
Every rule object has `source` (official URL), `quote` (text from that page; `[...]` marks an elision and long dashes are written as hyphens) and `verified` (date). Megabytes are converted to bytes as 1 MB = 1,000,000 bytes, the stricter reading; the original wording stays in `max_size_documented`. The schema is generic on purpose: LinkedIn, Viber or email can be added as new files without code changes.
`channels/*.json` is the single source. `npm run sync-data` copies it into `src/data.generated.ts` and `python/messaging_rules/data/`, and both test suites fail if a copy drifts.
## How the rules are verified
- Values come only from official pages: `developers.facebook.com`, `core.telegram.org` and `docs.x.com`. Third-party articles are used at most to find the official page, never for a value.
- If a value could not be confirmed on an official page it is left out rather than guessed. Not included at the last verification:
- **X:** maximum DM text length (the current v2 reference has a `dm-text-too-long` error but no number), and size limits beyond the media upload categories.
- **Telegram:** maximum number of inline keyboard buttons or rows.
- **WhatsApp:** per-user marketing template limits and exact per-category rules beyond the three categories.
- **Messenger:** One-time Notification (still mentioned on the policy page, current status unclear) and message tags other than the four listed.
- **Instagram:** marketing messages and utility messages.
- `npm test` checks that every rule has a source, a quote and a verified date, that every cited URL is an official host and is listed in `sources`, and that the generated files are current.
## Report a rule change
Platforms change these rules often. If something is out of date, open an issue with the [rule change template](.github/ISSUE_TEMPLATE/rule-change.md). It needs a link to the **official** page that shows the new value; changes backed only by blogs or vendor help centers are not accepted. Pull requests: edit `channels/<id>.json` (with `source`, `quote`, `verified`), then run `npm run sync-data && npm run generate-tables && npm test`.
## Limits
- This is not legal advice and not a compliance guarantee. Platforms change rules without notice; check the `verified` dates and the linked pages before relying on a value.
- The library checks timing and documented limits. It cannot know whether a user opted in, whether your app has the Human Agent permission, whether a template is approved, or what a recipient's privacy settings are; those come back as `conditions`.
- Window logic uses the time you pass. Pass the newest inbound message time: on WhatsApp every user message or call restarts the 24 hours.
- Some platform statements are approximate ("about 30 messages per second", "may last up to 7 days"); the data marks them as documented.
## Contributing
See [CONTRIBUTING.md](CONTRIBUTING.md). Tests: `npm test` (TypeScript, schema and generated files) and `cd python && python -m pytest`.
## License
MIT, see [LICENSE](LICENSE). The data, code and generated tables are all under the same license. Quotes from platform documentation are short excerpts kept for verification and remain the property of their publishers.
Built and maintained by [Pinlyx](https://pinlyx.com/?utm_source=github&utm_medium=readme&utm_campaign=messaging-rules), the omnichannel inbox and AI agent that enforces these rules across one inbox for every channel.
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessOutdated data