CLI & GuardrailsCLIDiscordAI AgentsPython

Giving AI Agents Safe Access to Discord Without MCP Schema Bloat

Why I built a REST-first Discord CLI with 89 commands, operator policy ceilings, offline dry-run confirmation tokens, and random-nonce prompt-injection boundaries.

By Solomon Wakhungu6 min read
Surface area89 cmdsOrganized across 20 command groups
Policy tiers3 levelsRead-only, allow-write, allow-destructive
TransportREST-firstNo persistent bot daemon or WebSocket

One public message should not be able to delete a channel

One message posted in a public Discord channel can tell your AI agent to delete a channel or kick a member, and an unrestricted bot token will let it. On top of that, exposing all 89 Discord operations as eager MCP (Model Context Protocol) tools dumps a huge block of JSON schemas into your prompt before the agent even knows whether it needs Discord.

I measured the full command manifest in this repository: 20.5 KB minified (roughly 5,100 tokens) and 42.7 KB pretty-printed. Even with lazy MCP tool loading, I still wanted shell composability with jq, offline schema discovery, standard Unix exit codes, and policy enforcement that lives outside the model's prompt.

I built discord-cli (distributed on PyPI as discordcli-agents) as a headless, JSON-first CLI with deterministic safety policies enforced inside the tool before any network request opens.

Why a REST-first CLI beats a persistent bot daemon

Most Discord libraries assume you are running a long-lived bot process connected over a WebSocket gateway. That model makes sense for interactive slash-command bots, not for a cron job, a GitHub Action, or an agent running one command.

discord-cli defaults to REST-first execution. It authenticates with your bot token, runs one command against Discord's REST API, prints a consistent JSON envelope, and exits. Webhook sends skip bot authentication altogether, and WebSocket gateway mode stays opt-in for the rare workflows that need it.

Instead of loading 89 tool schemas into every agent turn, the CLI pairs with a compact agent skill and runtime self-description commands. An agent can list commands with their risk levels and pull the exact JSON Schema for one subcommand only when it needs it.

Flags can tighten your limits, never loosen them

Every one of the 89 commands across 20 groups carries explicit risk metadata: read, write, or destructive. Dynamic commands like raw API requests or inactive-member pruning compute their risk from the actual HTTP method or flags, and unknown commands fail closed as write.

Guardrail architecture
How discord-cli keeps agent calls bounded from CLI ingress to JSON output
1. Policy Gate
Monotonic Ceilings
Env policy tier, guild/channel/group allowlists, and mutation caps. Flags can only tighten.
2. Confirmation
Dry-Run & Bound Token
Offline dry-run returns a deterministic confirmation token tied to command, guild, and args.
3. Transport
REST-First Client
One-shot Discord REST call with fail-closed human selectors and zero persistent daemon.
4. Safe Output
Nonce Envelope & PII Scrubbing
Wraps external text in random 64-bit nonce XML tags and redacts tokens, keys, and emails.
5. Observability
JSON Envelope & Audit Log
Consistent JSON payload, semantic exit codes, and secret-free JSONL audit records.
Operator environment ceilings are evaluated before any Discord network request opens. Outgoing writes can be previewed offline with dry-run confirmation tokens, and incoming text can be isolated in random-nonce boundaries.

Operators lock down an agent using environment variables for policy ceiling (read-only, allow-write, or allow-destructive), allowed guild IDs, allowed channel IDs, allowed command groups, and maximum bulk deletions. Those limits follow a monotonic ceiling rule: command-line flags can only tighten an operator's environment setting, never loosen it.

If an operator sets a read-only ceiling in the environment and a prompt-injected agent passes allow-destructive on the command line, the stricter environment ceiling silently wins. Read commands still work, while any write or delete command is rejected with semantic exit code 6 before any network connection opens.

For mutations, universal dry-run mode intercepts any write or destructive command offline and returns the execution plan plus a deterministic confirmation token bound to the command, guild ID, and canonicalized arguments (signed with HMAC, a keyed cryptographic signature, when an operator secret is set). In token-only confirmation mode, the simple yes flag is disabled so destructive actions require an operator-reviewed dry-run token.

Defending against prompt injection and opaque snowflake IDs

Reading messages, usernames, channel topics, or audit logs from a Discord server means pulling attacker-controlled text straight into your model's context window. To draw a clear boundary between instructions and external data, the untrusted-envelope flag wraps every external string field in a fresh random 64-bit nonce (a one-time random string) XML tag.

For example, a retrieved message arrives wrapped inside matching untrusted_dcli_4337fdc0... tags generated fresh for that single invocation, and any spoofed closing tags inside the user's message are escaped automatically so an attacker posting in Discord cannot guess the tag or break out of the boundary.

Turning on PII redaction scrubs leaked credentials (such as bot tokens, API keys, and webhook URLs) and email addresses before the JSON reaches the model. Optional JSONL audit logging records every invocation with timing, risk, and exit code without writing bot tokens to disk.

On the usability side, memorizing 18-digit Discord snowflake IDs is miserable for humans and error-prone for agents. discord-cli accepts human selectors like #announcements, category-qualified paths, role names, member handles, and full Discord message URLs. If a selector matches more than one channel or role, resolution fails closed with a structured candidate list instead of silently picking the first hit.

Distribution for real CI workflows, and key trade-offs

A CLI that only runs from a local checkout never makes it into production automation. I package discord-cli on PyPI (as discordcli-agents) and Homebrew for local developer machines, plus a Distroless container image and composite GitHub Action so CI workflows can run it without managing a Python environment.

Trade-offs to keep in mind

REST-first execution avoids maintaining a WebSocket cache, which means commands that list or resolve large servers make live HTTP calls and remain subject to Discord's API rate limits and privileged intent toggles for member lists and message content. Also, because third-party entry-point plugins run in the same Python process, locked-down agent setups should disable plugins alongside setting policy ceilings.

Install it and preview a guarded workflow

Install the CLI with uv (the PyPI package is discordcli-agents and the installed command is discord-cli):

Install with uv
uv tool install discordcli-agents

Or install through Homebrew on macOS and Linux:

Install with Homebrew
brew install 1solomonwakhungu/tap/discordcli-agents

Offline command discovery and dry-run previews work without any Discord credentials, while live read commands like channel list need your bot token and target server ID:

Discover offline, preview a write, and run a guarded read
discord-cli describe list --compact
discord-cli --dry-run message send "#releases" --content "Deploy finished"

export DISCORD_BOT_TOKEN="your-bot-token"
export DISCORD_GUILD_ID="your-server-id"
DISCORD_CLI_POLICY=read-only discord-cli --untrusted-envelope --redact-pii channel list

You can grab the bundled agent skill, CI recipes, and full policy reference from the GitHub repository.

View all posts
Agent Verification · 6 min read

Your Coding Agent Cited Line 48 Without Ever Opening the File

Why I built a deterministic transcript verifier that checks file citations, quoted code, and 'no other callers' claims in under a millisecond without calling another model.

Read post
Agent Memory · 6 min read

Context Compaction Keeps Erasing Your Rules Right When Precision Matters

How compact-ledger captures verbatim user constraints, mid-session overrides, and failing test trajectories before compaction and re-injects them in about 50 milliseconds.

Read post
Agent Reliability · 7 min read

Stopping AI Agents from Double-Posting When Tools Time Out

Putting a local SQLite write-ahead journal, deterministic preflight rules, and read-only crash reconciliation in front of mutating MCP and CLI calls.

Read post