MikroTik MCP / Docs / Contributing

Contributing

Thank you for your interest in contributing to the MikroTik MCP server. This MCP (Model Context Protocol) server provides tools for managing MikroTik RouterOS devices. Contributors can extend functionality by adding tools to a feature area, or by adding a new feature area.

Project structure

The codebase splits into a src/mcp_mikrotik/ package (the server and its tools, one package per feature area), a tests/ tree (unit + integration suites) and the reference pages under docs/reference/:

repository layout
src/mcp_mikrotik/
├── scope/          # The tools: one package per feature area (see "Feature areas" below)
│   ├── _shared/    #   helpers used by several areas (quoting, selectors)
│   ├── firewall/   #   an area: __init__.py, filter.py, nat.py, raw.py, ...
│   └── ...
├── app.py          # MCPServer instance, ToolAnnotation constants, one import per area
├── config.py       # Configuration (pydantic-settings, CLI args, env vars)
├── configured_mcp_server.py  # Read-only filtering, sensitive hiding, IP allowlist
├── connector.py    # Runs one command over a fresh SSH connection
├── http_security.py  # IP allowlist for the HTTP transports
├── inventory.py    # Multi-device inventory
├── mikrotik_ssh_client.py  # Low-level SSH client
├── safe_mode.py    # RouterOS safe mode sessions
├── sensitive.py    # Credential redaction
└── server.py       # Entry point: CLI parsing and transport selection

tests/
├── integration/    # Integration tests using testcontainers
└── unit/
    ├── scope/      # Tests of the tools: scope/<area>/ for one area, scope/ for tests that span areas
    └── ...         # Everything else: connector, config, ssh, app, ...

docs/reference/     # Reference pages, one folder per feature area (the same areas as scope/)

Feature areas

Everything for one feature lives in one place: a package under src/mcp_mikrotik/scope/, its tests under tests/unit/scope/<area>/ and its reference pages under docs/reference/<area>/.

AreaWhat belongs in itModules
devicesThe managed devices themselves: the inventory and the safe-mode sessioninventory, safe_mode
dhcp/ip dhcp-server and /ipv6 dhcp-serverdhcp
dns/ip dnsdns
firewall/ip firewall and /ipv6 firewall, IPv4 and IPv6 side by sidefilter, ipv6_filter, nat, raw, ipv6_raw, address_list
interfaces/interface, any typegeneric, vlan, bridge, wireguard, wireless, poe
ip/ip and /ipv6 menus that have no area of their ownaddress, ipv6_address, pool, neighbors, services
monitoringWays to observe a device: logs, Netwatch and the diagnostic tools (ping, traceroute, torch, packet capture, CPU profile)logs, netwatch, diagnostics
queue/queuequeue
routingRoutes and routing tablesroutes
system/system: resource information, scheduler and scripts, backups and filesinfo, scheduler, backup
users/userusers
vpnVPN protocols other than WireGuard (an /interface type, so it lives in interfaces)ipsec

The rules:

Development setup

The project uses uv as its single Python toolchain; install uv first. After that, provisioning a working environment is two commands:

# clone and provision
$ git clone https://github.com/wiresage/mikrotik-mcp.git
$ cd mikrotik-mcp
$ uv sync --frozen

uv sync --frozen installs the exact versions pinned in uv.lock (including the dev dependency group) without re-resolving, so a clean checkout gets the same environment CI uses. uv creates and manages the .venv for you.

AGENTS
Working with an AI coding agent? The repository's AGENTS.md collects the setup commands, tool-writing rules and the RouterOS behaviour that has caused bugs before, so the agent has them up front.

Running the tests

# run the suites
$ uv run pytest                        # full suite
$ uv run pytest -m "not integration"   # unit tests only (no Docker needed)
$ uv run pytest -m integration         # integration tests (needs Docker)

No manual dependency install is needed — uv run executes against the locked environment.

Changing dependencies (regenerating the lockfile)

When you add, remove, or change a dependency in pyproject.toml, regenerate and commit the lockfile in the same PR:

# regenerate the lockfile
$ uv lock    # update uv.lock to match pyproject.toml
$ uv sync    # apply it to your environment

CI runs a lockfile-drift gate (uv lock --check): a PR that changed pyproject.toml without a matching uv.lock fails with a plain-language message saying the lockfile is out of date. Commit the updated uv.lock and the gate passes.

Keep these in mind when you touch dependencies:

Contributing new features

To add a new MikroTik feature/scope to the project, follow these five steps.

1. Create the tool module

Find the area for your feature in the table above and create a new Python file in that package, for example src/mcp_mikrotik/scope/firewall/mangle.py. If no area fits, create a new package for it (see step 3).

Your module should:

TIP
Always register tools with annotate(BASE, "Title") — passing a bare annotation constant skips the human-readable title and is considered incorrect.
# Example structure — src/mcp_mikrotik/scope/my_area/my_feature.py
from typing import Optional

from mcp.server.mcpserver import Context

from ...app import mcp, WRITE, annotate
from ...connector import execute_mikrotik_command
from .._shared.quoting import ros_quoted


@mcp.tool(name="create_my_resource", annotations=annotate(WRITE, "Create My Resource"))
async def mikrotik_create_my_resource(
    ctx: Context,
    name: str,
    comment: Optional[str] = None,
    device: Optional[str] = None,
) -> str:
    """Creates a resource on the MikroTik device."""
    await ctx.info(f"Creating resource: name={name}")

    quoted_name = ros_quoted(name)
    cmd = f'/my/feature add name="{quoted_name}"'
    if comment:
        cmd += f' comment="{ros_quoted(comment)}"'

    # A successful add prints nothing, so any output is a refusal.
    result = await execute_mikrotik_command(cmd, ctx, device=device)
    if result.strip():
        return f"Failed to create resource: {result}"

    count = await execute_mikrotik_command(
        f'/my/feature print count-only where name="{quoted_name}"', ctx, device=device
    )
    if count.strip() == "0":
        return f"Failed to create resource: '{name}' was not found afterwards."

    return f"Resource '{name}' created."

2. Choose the right tool annotation

Import the appropriate annotation constant from app.py and pass it via @mcp.tool(annotations=...):

ConstantUse for
READReads that change nothing on the device. /export file=... and /system backup save write files, so they are not reads
WRITENon-idempotent writes (add, create)
WRITE_IDEMPOTENTIdempotent writes (set, update, enable, disable, move)
DESTRUCTIVERemovals (remove, flush, disconnect)
DANGEROUSRestore, import, reset, and anything that can lock you out

--read-only exposes only READ tools, so this choice is a safety control.

3. Register your module

Add the module's name to the from . import (...) list of its area's __init__.py, one name per line:

# src/mcp_mikrotik/scope/firewall/__init__.py
from . import (  # noqa: F401
    address_list,
    filter,
    ipv6_filter,
    ipv6_raw,
    mangle,
    nat,
    raw,
)

The import triggers the @mcp.tool() decorators, which register your tools with the MCP server. A module its area does not import registers nothing, so tests/unit/scope/test_layout.py fails if you forget this step.

A new area is a new package: create src/mcp_mikrotik/scope/my_area/__init__.py with a docstring that says what belongs in the area and the from . import (...) list, then add the package to the import list in src/mcp_mikrotik/app.py (one name per line, in alphabetical order, so two pull requests that add areas rarely conflict):

# src/mcp_mikrotik/app.py
from mcp_mikrotik.scope import (  # noqa: F401, E402
    devices,
    ...
    my_area,
    ...
)

A new area also gets a folder for its tests (tests/unit/scope/my_area/ with an __init__.py) and one for its reference pages (docs/reference/my_area/). Then add:

4. Write tests

Put unit tests in tests/unit/scope/<area>/test_<module>.py (a test that spans several areas goes in tests/unit/scope/). The smoke test (tests/unit/scope/test_smoke.py) finds your module by itself, so there is no list to update. Replace the connector with FakeExecutor, assert the exact command, and cover the refusal and "nothing matched" paths as well as success:

# tests/unit/scope/my_area/test_my_feature.py
import asyncio

from mcp_mikrotik.scope.my_area import my_feature
from tests.conftest import FakeExecutor


def test_create_sends_expected_command(ctx, monkeypatch):
    fake = FakeExecutor()
    monkeypatch.setattr(my_feature, "execute_mikrotik_command", fake)

    result = asyncio.run(my_feature.mikrotik_create_my_resource(ctx, name="r1"))

    assert fake.commands[0] == '/my/feature add name="r1"'
    assert "created" in result

Integration tests go in tests/integration/, use the @pytest.mark.integration marker, and run against a RouterOS container started with testcontainers. See tests/integration/test_mikrotik_user_integration.py.

5. Test your implementation

Before submitting, ensure your implementation works:

  1. Run the unit tests:
# run the unit suite (no Docker needed)
$ uv run pytest -m "not integration"
  1. Use MCP Inspector: test your tools interactively using the MCP Inspector.
# launch the inspector against your server
# Test your MCP server (stdio transport)
$ npx @modelcontextprotocol/inspector uv run mcp-server-mikrotik
  1. Manual testing: test with a real MikroTik device to ensure commands work correctly.

Transport modes

The server supports three transport modes:

Configure via CLI (--mcp.transport) or environment variable (MIKROTIK_MCP__TRANSPORT).

Development guidelines

Code style

MikroTik command guidelines

Testing requirements

API coverage

docs/api-coverage.yml is the source of truth for the RouterOS menus and commands the MCP intends to cover. docs/api-coverage.md is generated from it; never edit it by hand. The generated checklist is the checked/unchecked progress view for developers and users, and it is summarised on the API coverage page.

When adding or changing a tool:

  1. Update docs/api-coverage.yml:
    • status: implemented, partial, planned, legacy or not_applicable.
    • tools: registered MCP tool names for implemented, partial and legacy. not_applicable may also list the tool that explains it; planned commands must not list tools.
    • params: manual argument names (vlan-id, not vlan_id; configuration.ssid for nested arguments).
    • accepted_gaps: intentional omissions of manual arguments. Read-only fields and flags are excluded from the unmapped-argument check automatically, so do not add them just to silence warnings.
    • notes: explain partial, legacy, not_applicable, or a non-obvious caveat. Menu-level notes explain the scope; do not repeat the tool docstring.
    • manual_paths: menus documented as separate command pages. Include the parent page when it has arguments.
    • allow_missing_manual: only for commands with no standalone manual page.
    • server_tools: tools that do not map to one menu command (kind + note).
    • top-level excluded: out-of-scope menus, with a reason.
  2. Run uv run python scripts/api_coverage.py --write.
  3. Run uv run python scripts/api_coverage.py --check; CI runs the same check.
  4. Run uv run pytest -m "not integration".
  5. Commit docs/api-coverage.yml, the regenerated docs/api-coverage.md, and the tool code, tests and docs.

If the tool's parameters change, update its page under docs/reference/<area>/.

The Check API coverage workflow does not update the lockfile (docs/manual.lock.yml) or the manifest (docs/api-coverage.yml): review the api-coverage-report artifact, then update docs/manual.lock.yml and the manifest deliberately, run --write, and commit. Use --strict (or the workflow's strict input) when warnings should fail the run. The corpus is not committed; only the lockfile metadata is.

PR demo GIF

Every pull request that targets master gets one comment from the PR demo workflow: a short GIF that illustrates the change, a title, a one-line description and a #demonstration_<pr-title> tag (spaces become -). The comment is updated on every push. The GIF is drawn by AI from the diff, so it is an illustration, not a recording; check it against the code.

The workflow runs from master and never executes code from the pull request: the model gets no tools, scripts/pr_demo.py validates its storyboard and draws the GIF, and the GIFs are stored on the orphan pr-demos branch. Re-run it for a pull request from the Actions tab (PR demo, Run workflow, with the number).

Discord notifications

The Discord PR notifications workflow announces every pull request in the maintainers' Discord channel, including the ones that are never merged. When a pull request is opened it posts an embed and starts a thread from it. The embed shows the author, the branch (owner:branch → base) and the size of the change. The thread gets the commits of the pull request (each commit once, also after a force push), each as subject with its short hash as a link and the author's name, plus the committer's name when somebody else committed it, and a line when the pull request is reopened, merged or closed (with who merged or closed it). The workflow runs from master with pull_request_target, so pull requests from forks are announced too; it never checks out or runs anything from the pull request, and every message turns mentions off.

It needs the secret DISCORD_BOT_TOKEN and the variables DISCORD_GUILD_ID and DISCORD_CHANNEL_ID. The bot needs these permissions in the channel, as an overwrite for its role when @everyone is denied: View Channel, Send Messages, Embed Links, Create Public Threads, Send Messages in Threads and Read Message History. When a run fails, its log shows what Discord answered (Missing Permissions means one of the permissions above is missing), and Re-run failed jobs repeats the run without a new event. Do not rename a thread: the workflow finds the thread of a pull request by PR #<number> at the start of its name. Discord archives a thread that was quiet for 7 days and the next event opens it again; a thread older than the 100 most recently archived ones is not found, and that pull request gets a new thread.

Commit format and versioning

This project uses GitVersion for automatic semantic versioning based on commit messages, and follows the Conventional Commits specification.

All pull requests merge directly to master. There are no develop or release branches. A merge publishes a new version only when it changes a shipped file: src/**, pyproject.toml, uv.lock, Dockerfile, .dockerignore, docker-entrypoint.sh or server.json.

Version format

Published versions use a 4-part format: MAJOR.MINOR.PATCH.BUILD

PositionLabelIncremented by
1 (MAJOR)x.0.0.0Never — frozen at 0
2 (MINOR)0.x.0.0feat: commits
3 (PATCH)0.0.x.0fix:, chore:, and other change commits
4 (BUILD)0.0.0.xAlways 0
—no changedocs: commits
MAJOR
The major version is intentionally frozen at 0. Never use +semver: breaking or +semver: major without explicit approval.

Quick reference

Commit prefixExampleVersion change
feat:feat: add queue management toolsMinor bump: 0.5.0 → 0.6.0
fix:fix: handle empty SSH responsePatch bump: 0.5.0 → 0.5.1
chore:chore: update dependenciesPatch bump: 0.5.0 → 0.5.1
refactor:refactor: simplify connectorPatch bump: 0.5.0 → 0.5.1
perf:perf: cache SSH connectionPatch bump: 0.5.0 → 0.5.1
ci:ci: add Python 3.13 to matrixPatch bump: 0.5.0 → 0.5.1
test:test: add queue smoke testsPatch bump: 0.5.0 → 0.5.1
docs:docs: update safe mode guideNo bump
doc:doc: fix typoNo bump
(untyped)update somethingPatch bump (fallback)
+semver: breakingfooter tagMajor bump (emergency only)

Format

# commit anatomy
<type>[optional scope]: <description>

[optional body]

[optional footer(s)]

Types

TypeDescriptionVersion effect
featNew feature or toolMinor bump
fixBug fixPatch bump
choreDependency updates, toolingPatch bump
refactorCode restructuringPatch bump
perfPerformance improvementPatch bump
ciCI/CD pipeline changesPatch bump
testTest additions or updatesPatch bump
styleCode formattingPatch bump
buildBuild system changesPatch bump
revertReverting a previous commitPatch bump
docs / docDocumentation onlyNo bump

Scopes (optional)

Scopes indicate which area of the codebase is affected:

Examples

# feat: new feature, minor bump
feat(queue): add simple queue and queue tree management

Implements create, list, get, update, remove, enable, and disable
operations for queue types, queue trees, and simple queues.

Result: 0.5.0.0 → 0.6.0.0

# fix: bug fix, patch bump
fix(safe-mode): handle ANSI escape sequences in <SAFE> prompt detection

Result: 0.5.0.0 → 0.5.1.0

# chore: maintenance, patch bump
chore: bump paramiko to 3.5.1 for CVE-2024-xxxx

Result: 0.5.0.0 → 0.5.1.0

# docs: documentation, no bump
docs: add queue and safe-mode reference pages

Result: version unchanged — the pipeline skips the PyPI publish.

Mixed PR. When a PR contains both feat: and docs: commits, GitVersion picks the highest increment across all commits. The result is a minor bump.

Version release process

  1. A PR that changes a shipped file is merged to master
  2. GitVersion calculates the new version from the commit history
  3. GitHub Actions builds the package with the calculated version
  4. Unit tests run across Python 3.10 / 3.11 / 3.12
  5. The package is published to PyPI (skip-existing: true — duplicate versions are silently skipped, never fail the pipeline)
  6. A git tag and GitHub Release are created automatically

You never need to manually bump version numbers or create tags.

Best practices

Branching strategy

Branches for new pull requests carry the issue number they address:

# branch name format
<type>/issue-<number>-<short-description>
# examples
feat/issue-123-branch-one
fix/issue-#-branch-two

This makes every branch self-documenting: the type tells reviewers what kind of change to expect, and the issue number links the work back to its context (or # states explicitly that no issue exists, rather than leaving reviewers to search for one).

Submitting a pull request

  1. Fork the repository and create your feature branch from master, named according to the branching strategy above
  2. Implement your changes following the guidelines above
  3. Run all tests to ensure nothing is broken
  4. Test with MCP Inspector to verify tools work correctly
  5. Write descriptive commit messages following the format above
  6. Submit a pull request with:
    • Clear description of what you've added
    • Reference to any related issues
    • Screenshots or examples if applicable
    • Confirmation that tests pass
    • Indication of version bump impact (minor, major, patch, or none)
  7. Assign the pull request to yourself. Use Assignees in the sidebar, or open it with gh pr create --assignee @me. GitHub only lets people with write access set assignees; if you cannot, a maintainer assigns the pull request to you, so every contribution is listed under the contributor's name.

Getting help

Code review process

All contributions go through code review to ensure:

Thank you for contributing to MikroTik MCP. Your additions help make RouterOS management more accessible through the Model Context Protocol.