mcp-server-mattermost
AGENTS.md52 starsChanged 10 months agoMITView on GitHub
MCP server for Mattermost integration. Exposes Mattermost REST API operations as MCP tools for AI assistants (Claude Desktop, Cursor). Architecture: Required environment variables: - MATTERMOST_URL - Mattermost server URL - MATTERMOST_TOKEN - Bot or user access token (conditional: required unless MATTERMOST_ALLOW_HTTP_CLIENT_TOKENS is enabled) Optional: - MATTERMOST_TIMEOUT (default: 30) - MATTERMOST_MAX_RETRIES (default: 3) - MATTERMOST_VERIFY_SSL (default: true) - MATTERMOST_LOG_LEVEL (default: INFO) - MATTERMOST_LOG_FORMAT (default: json) - Log format: 'json' for production, 'text' for development - MATTERMOST_API_VERSION (default: v4) - MATTERMOST_MAX_CONNECTIONS (default:…
- Commits and pushes
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about code style.
Of the AGENTS.md files we read, the 35,337 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
The file
Show its rules and text
We split this AGENTS.md into the rules it gives an agent
13 rules. About 0 are common, 6 are distinctive, and 7 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈6
Distinctive · estimate
This author's own choices. Worth a look.
7
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 106
Use respx for mocking httpx requests.
- Very specific: line 172
Use Capability enum from enums.py — never raw strings:
- Distinctive: line 223
All tool functions use this pattern:
- Distinctive: line 238
Write project artifacts in English, including documentation, code comments, commit messages, and issue and PR/MR titles and descriptions.
- Very specific: line 243
Do not include Co-Authored-By: trailers for AI agents in commit messages.
- Very specific: line 250
Update version in pyproject.toml
- Very specific: line 251
Update __version__ fallback in src/mcp_server_mattermost/__init__.py
- Very specific: line 252
Update CHANGELOG.md with changes
- Distinctive: line 256
Create GitHub Release from tag → triggers PyPI publish
- Distinctive: line 260
Before committing, always run the full lint suite and fix any issues:
- Distinctive: line 269
Do NOT commit code that has lint, type, or test errors.
- Very specific: line 273
When using markdown (images, lists, bold) inside HTML blocks (<div>, <details>) in MkDocs — add md_in_html extension and markdown attribute …
- Very specific: line 274
When adding CSS class to an image in MkDocs — use attr_list extension with !alt{ .classname } instead of wrapping in <div class="...">.
≈ “Common” is an estimate: at least 1 in 5 of the 45,344 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
Project Overview
MCP server for Mattermost integration. Exposes Mattermost REST API operations as MCP tools for AI assistants (Claude Desktop, Cursor).
Architecture:
MCP Client (Claude Desktop, Cursor)
↓ (stdio JSON-RPC)
FastMCP Server
├── Tools Layer (channels, messages, posts, users, teams, files, bookmarks)
├── Pydantic Models (validation + schema generation)
└── MattermostClient (async HTTP with retry)
↓ (HTTPS)
Mattermost Server (REST API v4)Documentation References
- FastMCP: https://gofastmcp.com/llms.txt - Use for implementation details when working with FastMCP
- Mattermost API: https://api.mattermost.com/ - REST API v4 reference
Commands
# Install dependencies
uv sync
# Run tests
uv run pytest
# Run specific test file
uv run pytest tests/test_config.py -v
# Lint
uv run ruff check src tests
# Format
uv run ruff format src tests
# Type check
uv run mypy src
# Run the server
uv run mcp-server-mattermostCode Style
- Python 3.10+ (use
list[],dict[],X | Nonesyntax) - 120-character line length
- Google-style docstrings
- Type hints required (mypy strict mode)
- Two blank lines after imports
- Ruff with ALL rules enabled (see pyproject.toml for exceptions)
Key Source Files
src/mcp_server_mattermost/__init__.py- Package entry, exportsmain()and__version__src/mcp_server_mattermost/server.py- FastMCP instance creation, lifespan, FileSystemProvidersrc/mcp_server_mattermost/deps.py- Dependency injection providers (get_client)src/mcp_server_mattermost/auth.py- MattermostTokenVerifier for per-client token authsrc/mcp_server_mattermost/client.py- Async HTTP client with retry logicsrc/mcp_server_mattermost/config.py- Settings via pydantic-settings (env vars prefixedMATTERMOST_)src/mcp_server_mattermost/exceptions.py- Exception hierarchy (MattermostMCPErrorbase)src/mcp_server_mattermost/logging.py- Logging setup (stderr per MCP spec)src/mcp_server_mattermost/middleware.py- FastMCP middleware for error handlingsrc/mcp_server_mattermost/enums.py- Capability and ToolTag enums for tool metadatasrc/mcp_server_mattermost/tools/- MCP tool implementations by categorysrc/mcp_server_mattermost/models/- Pydantic models for validation
Configuration
Required environment variables:
MATTERMOST_URL- Mattermost server URLMATTERMOST_TOKEN- Bot or user access token (conditional: required unlessMATTERMOST_ALLOW_HTTP_CLIENT_TOKENSis enabled)
Optional:
MATTERMOST_TIMEOUT(default: 30)MATTERMOST_MAX_RETRIES(default: 3)MATTERMOST_VERIFY_SSL(default: true)MATTERMOST_LOG_LEVEL(default: INFO)MATTERMOST_LOG_FORMAT(default: json) - Log format: 'json' for production, 'text' for developmentMATTERMOST_API_VERSION(default: v4)MATTERMOST_MAX_CONNECTIONS(default: 100) - Max HTTP connections in the shared poolMATTERMOST_MAX_KEEPALIVE_CONNECTIONS(default: 20) - Max idle keepalive connections, clamped to max connectionsMATTERMOST_KEEPALIVE_EXPIRY(default: 30.0) - Idle keepalive connection lifetime in secondsMATTERMOST_ALLOW_HTTP_CLIENT_TOKENS(default: false) - Allow HTTP clients to use their own Mattermost tokensMATTERMOST_HTTP_HOST_ORIGIN_PROTECTION(default: none) - Host/Origin protection:off,auto, orstrictMATTERMOST_HTTP_ALLOWED_HOSTS(default: none) - Extra allowedHostheader values (JSON array or comma-separated)MATTERMOST_HTTP_ALLOWED_ORIGINS(default: none) - Extra allowedOriginheader values (JSON array or comma-separated)
Testing
Unit Tests
Tests use pytest with pytest-asyncio. Test fixtures in tests/conftest.py:
clean_env- Removes MATTERMOST_* env vars for test isolationmock_settings- Sets valid test environment variables
Use respx for mocking httpx requests.
Integration Tests
Integration tests in tests/integration/ use fastmcp.Client for in-memory MCP testing.
Key insight: FastMCP provides Client(server) that connects directly to server instance
via in-memory transport — no subprocess, no network overhead, full MCP protocol.
from fastmcp import Client
from mcp_server_mattermost.server import mcp
async def test_list_public_channels(mattermost_env):
async with Client(mcp) as client:
result = await client.call_tool("list_public_channels", {"team_id": team_id})
assert any(ch["name"] == "town-square" for ch in result.data)What this tests:
- MCP protocol (tools/list, tools/call, JSON-RPC)
- Pydantic validation at tool layer
- FastMCP routing
- MattermostClient HTTP logic
- Real Mattermost API
References:
Run integration tests:
# With Testcontainers (needs Docker)
uv run pytest tests/integration
# Against external server
export MATTERMOST_URL=https://your-server.com
export MATTERMOST_TOKEN=your-bot-token
uv run pytest tests/integrationMCP Tool Annotations
FastMCP defaults (important to remember):
readOnlyHint: false — explicitly setTruefor read-only operationsdestructiveHint: true — explicitly setFalsefor reversible write operationsidempotentHint: false — explicitly setTrueif repeated call = no-op
Operation classification:
- Read-only →
readOnlyHint=True, idempotentHint=True - Write idempotent (join, add_reaction, pin) →
destructiveHint=False, idempotentHint=True - Write non-idempotent (post_message, create_channel) →
destructiveHint=False - Destructive (delete_message) → no annotations needed (default true)
"Destructive" = irreversible loss of data.
Tool Capability Metadata
Each tool declares a capability in meta for agent-based filtering:
read— retrieves data, no side effects (get, list, search)write— modifies state within existing resources (post, update, join, pin, react, upload)create— creates new top-level entities (channels, DMs)delete— permanently destroys a resource
Use Capability enum from enums.py — never raw strings:
from fastmcp.tools import tool
from mcp_server_mattermost.enums import Capability, ToolTag
@tool(
annotations={"readOnlyHint": True, "idempotentHint": True},
tags={ToolTag.MATTERMOST, ToolTag.CHANNEL},
meta={"capability": Capability.READ},
)
async def list_public_channels(...):Classification rules:
create= only for new standalone entities (channels, DMs)write= all other modifications, including "create" operations on dependent resources (bookmarks, messages, reactions, files exist only inside a channel)delete= resource permanently ceases to exist- Each tool gets exactly one capability
Profiles are defined client-side, not server-side. The server provides capability labels, clients assemble profiles from them:
PROFILES = {
"reader": {"read"},
"writer": {"read", "write"},
"manager": {"read", "write", "create"},
"admin": {"read", "write", "create", "delete"},
}MCP Tool Description Best Practices
Description formula: WHAT it does + WHEN to use + DISAMBIGUATION
# Disambiguation example between similar tools:
"""Get recent messages from a channel.
Returns messages in reverse chronological order.
Use for reading channel conversation history.
For searching by keywords, use search_messages instead. # ← disambiguation
"""Code Patterns
FastMCP Dependency Injection
All tool functions use this pattern:
from fastmcp.dependencies import Depends
from mcp_server_mattermost.deps import get_client
client: MattermostClient = Depends(get_client), # noqa: B008The # noqa: B008 suppresses ruff's flake8-bugbear warning "Do not perform function calls
in argument defaults". This is intentional — Depends() is a FastMCP/FastAPI DI marker,
not a mutable default. The function call happens at request time, not at function definition.
Project Language
Write project artifacts in English, including documentation, code comments, commit messages, and issue and PR/MR titles and descriptions. Match the user's language in conversation.
Commit Messages
Do not include Co-Authored-By: trailers for AI agents in commit messages.
Human contributor co-authorship trailers are welcome.
Versioning
This project uses manual versioning:
- Update version in
pyproject.toml - Update
__version__fallback insrc/mcp_server_mattermost/__init__.py - Update
CHANGELOG.mdwith changes - Commit:
git commit -m "chore: bump version to X.Y.Z" - Tag:
git tag -a vX.Y.Z -m "Release vX.Y.Z" - Push:
git push origin main --tags - Create GitHub Release from tag → triggers PyPI publish
Pre-commit Checklist
Before committing, always run the full lint suite and fix any issues:
uv run ruff check src tests # lint
uv run ruff format src tests # format
uv run mypy src # type check
uv run pytest # testsDo NOT commit code that has lint, type, or test errors.
Lessons Learned
- When using markdown (images, lists, bold) inside HTML blocks (
<div>,<details>) in MkDocs — addmd_in_htmlextension andmarkdownattribute on the HTML tag, otherwise content renders as plain text - When adding CSS class to an image in MkDocs — use
attr_listextension with{ .classname }instead of wrapping in<div class="...">. Cleaner, no HTML needed
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

