diff --git a/docs/features/mcp-service.md b/docs/features/mcp-service.md index b0af63e65..e2d347a1b 100644 --- a/docs/features/mcp-service.md +++ b/docs/features/mcp-service.md @@ -102,7 +102,7 @@ from the API key automatically — long-lived sessions keep working ## Available Tools -**78 tools** across 11 categories: +**79 tools** across 11 categories: ### Project (14) @@ -232,13 +232,25 @@ they require a vision-capable model to be genuinely useful. Revisit later. | `server_version` | Get GNS3 server version | | `server_statistics` | Get server statistics (computes, projects, nodes) | -### Device Config (3) +### Device Config (4) | Tool | Description | |------|-------------| -| `device_config_send` | Push config commands to devices via console (Nornir + Netmiko). Supports Jinja2 `template` + `vars` | -| `device_show_run` | Run read-only show commands on devices. Supports Jinja2 `template` + `vars` | -| `vpcs_config_set` | Configure VPCS devices (IP, gateway, etc.) | +| `device_config_send` | Push config commands to devices via console (Nornir + Netmiko), batch and parallel. Supports Jinja2 `template` + `vars` | +| `device_show_run` | Run read-only show commands on devices (whitelist-enforced). Supports Jinja2 `template` + `vars` | +| `vpcs_config_set` | Configure VPCS devices in batch (Nornir + Netmiko, parallel, VPCS command syntax validated) — the VPCS counterpart of `device_config_send` | +| `device_skill_get` | Read device knowledge from the GNS3-Skills repository (list → topic index → single topic; same access protocol as the copilot's `device_skills` tool) | + +**Which tool when** — the console-facing tools divide the work by shape: + +| Scenario | Use | +|---|---| +| Push the same-shaped config to many network devices, one call | `device_config_send` (Jinja2 template + parallel fan-out) | +| Configure many VPCS PCs in one call | `vpcs_config_set` (parallel, VPCS syntax validated) | +| Inspect many devices read-only, one call | `device_show_run` (command whitelist — safe for AI) | +| Network OS console, any interaction | `device_config_send` / `device_show_run` (batch drivers manage config mode themselves) | +| Unfamiliar device: read its quirks before driving the console | `device_skill_get` (list first, then fetch by key) | +| VNC console | `node_console` (returns a websocat URL) | The tool connects to each device's console via telnet/SSH. Nodes must be in the `started` state (use `node_start` or `node_start_all`). Device type is auto-detected from the node's `device_type:` tag in GNS3. @@ -304,6 +316,18 @@ node_stop(project_id, node_id) node_start(project_id, node_id) ``` +#### Device Skills (`device_skill_get`) + +The GNS3-Skills repository (the same one the embedded copilot reads) carries per-device operational knowledge that the generic tools cannot know: FRR's console lands directly in vtysh (its ping has no `-c`, scripted config needs `do` prefixes), VPCS command syntax, IOS paging pitfalls, SR Linux's TUI-only CLI. `device_skill_get` exposes it to MCP clients with the copilot's multi-call protocol — list, then the device's topic index, then one targeted body: + +```python +device_skill_get(action="list") # 1. every loaded skill +device_skill_get(device_type="frr_vtysh") # 2. that device's skill + topic index +device_skill_get(device_type="frr_vtysh", topic="bgp") # 3. one targeted topic body +``` + +Step 2 returns the base skill plus the topic index; topic bodies load **only** on an explicit `topic` request (step 3). The key is passed back exactly as step 1 returned it. + ### Device Config Workflow ```mermaid diff --git a/gns3server/agent/mcp/__init__.py b/gns3server/agent/mcp/__init__.py index 3a2a6cbec..cfbd7389d 100644 --- a/gns3server/agent/mcp/__init__.py +++ b/gns3server/agent/mcp/__init__.py @@ -148,6 +148,7 @@ from .server import ( get_statistics_handler, get_version_handler, ) +from .skills import device_skills_handler from .snapshots import ( create_snapshot_handler, delete_snapshot_handler, @@ -2189,6 +2190,56 @@ async def vpcs_config_set( ) +@mcp.tool() +async def device_skill_get( + device_type: Annotated[ + str | None, + Field(description="Skill key exactly as action='list' returns it, e.g. 'frr_vtysh', 'cisco_ios_telnet'"), + ] = None, + action: Annotated[str | None, Field(description='"list" to enumerate skills; "get" (default) to fetch one')] = None, + topic: Annotated[ + str | None, + Field( + description='Protocol topic key from the topic index, e.g. "ospf", "bgp". ' + "Topic bodies load ONLY on an explicit topic request — every other call returns the base skill plus the topic index" + ), + ] = None, + detail: Annotated[str | None, Field(description='"index" | "summary" | "full" (default)')] = None, + issue: Annotated[str | None, Field(description="Single troubleshooting-issue key from the skill")] = None, +) -> list[dict[str, Any]]: + """Read device knowledge from the GNS3-Skills repository — BEFORE driving an unfamiliar console. + + TOKEN-EFFICIENT USAGE (same protocol as the copilot's device_skills tool): + 1. List every skill: device_skill_get(action="list") + 2. Device skill list (topics): device_skill_get(device_type="frr_vtysh") + 3. ONE targeted topic body: device_skill_get(device_type="frr_vtysh", topic="bgp") + + Step 2 returns the base skill plus the topic index; step 3 loads the + targeted body. Pass the key exactly as step 1 returned it. + Skills carry the operational quirks the generic tools cannot know: + FRR's console lands directly in vtysh (no -c on its ping, 'do' prefixes + inside scripted config), VPCS command syntax, IOS paging pitfalls. + + Requires the skills repository to be configured (cloned); when none is + loaded the error says so and action="list" returns an empty set. + + IF YOUR CLIENT OFFERS SUBAGENTS: on long tasks, delegate steps 1-2 + to a subagent and ask it to return the exact command/quirk snippets + you need — not a prose summary. The full skill bodies then never + occupy this conversation's context. + """ + params: dict[str, Any] = {"action": action} + if device_type is not None: + params["device_type"] = device_type + if topic is not None: + params["topic"] = topic + if detail is not None: + params["detail"] = detail + if issue is not None: + params["issue"] = issue + return await asyncio.to_thread(_run_handler_sync, device_skills_handler, params) + + # ── Auth‑wrapped Streamable HTTP app ────────────────────────────────── diff --git a/gns3server/agent/mcp/skills.py b/gns3server/agent/mcp/skills.py new file mode 100644 index 000000000..c4b8d9f11 --- /dev/null +++ b/gns3server/agent/mcp/skills.py @@ -0,0 +1,76 @@ +# +# Copyright (C) 2026 GNS3 Technologies Inc. +# Author: Yue Guobin +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# + +""" +device_skill_get — the MCP surface of the GNS3-Skills repository. + +The copilot's DeviceSkillsTool already proved the access pattern +(list -> topic index -> single topic; bodies load ONLY on an explicit +topic request). This handler reuses the same framework-free core — +get_skill() / list_available_skills() over SKILLS_REGISTRY — instead of +the LangChain tool shell, so both surfaces stay in step by construction +and share the SkillsManager hot reload. + +The protocol is multi-call by design: list -> a device's topic index -> +one topic body. The caller picks the key from the list and passes it +back unchanged; there is no name guessing in this layer. +""" + +import logging +from typing import Any + +log = logging.getLogger(__name__) + + +def device_skills_handler(params: dict[str, Any], gns3_ctx: dict[str, Any]) -> dict[str, Any]: + """List or fetch skills from the GNS3-Skills repository. + + action "list" -> every loaded skill (device_type, name, topic_count). + Otherwise one skill by the key the list returned. + """ + try: + from gns3server.agent.gns3_copilot.skills import registry + except Exception as e: + log.debug("device_skill_get: skills registry unavailable: %s", e) + return {"status": "failed", "error": f"Skills subsystem unavailable: {e}"} + + action = params.get("action") + if not action: + # No explicit action: list when nothing to get, get otherwise. + action = "list" if not params.get("device_type") else "get" + if action == "list": + skills = registry.list_available_skills() + return {"status": "ok", "count": len(skills), "skills": skills} + + device_type = params.get("device_type") + if not device_type: + return { + "status": "failed", + "error": "Provide device_type (the skill key)", + "hint": "device_skill_get(action='list') enumerates what is loaded", + } + + result = registry.get_skill( + device_type, + detail=params.get("detail", "full"), + issue=params.get("issue"), + topic=params.get("topic"), + ) + if "error" in result: + return {"status": "failed", **result} + return {"status": "ok", "skill": result} diff --git a/tests/agent/mcp/test_skills.py b/tests/agent/mcp/test_skills.py new file mode 100644 index 000000000..af1c537f6 --- /dev/null +++ b/tests/agent/mcp/test_skills.py @@ -0,0 +1,81 @@ +# +# Copyright (C) 2026 GNS3 Technologies Inc. +# Author: Yue Guobin +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# + +""" +Unit tests for the MCP device skills tool (registry faked, no I/O). +""" + +import pytest + +from gns3server.agent.gns3_copilot.skills import registry as skills_registry +from gns3server.agent.mcp.skills import device_skills_handler + +FAKE_SKILLS = { + "frr_vtysh": { + "name": "FRR", + "description": "vtysh console model", + "category": "device", + "topics": {"bgp": {"name": "BGP", "syntax": "router bgp "}}, + }, + "cisco_ios_telnet": {"name": "IOS", "description": "IOS quirks", "category": "device"}, + "gns3_vpcs_telnet": {"name": "VPCS", "description": "VPCS syntax", "category": "device"}, +} + + +@pytest.fixture(autouse=True) +def fake_registry(monkeypatch): + """Deterministic skills registry — the real one depends on whether the + skills repository has been cloned on this machine.""" + monkeypatch.setattr(skills_registry, "SKILLS_REGISTRY", FAKE_SKILLS) + + +class TestDeviceSkillsHandler: + def test_list(self): + result = device_skills_handler({"action": "list"}, {}) + assert result["status"] == "ok" + assert result["count"] == 3 + assert {s["device_type"] for s in result["skills"]} == set(FAKE_SKILLS) + + def test_no_args_defaults_to_list(self): + result = device_skills_handler({}, {}) + assert result["status"] == "ok" and result["count"] == 3 + + def test_get_by_key(self): + result = device_skills_handler({"device_type": "frr_vtysh"}, {}) + assert result["status"] == "ok" + assert result["skill"]["name"] == "FRR" + + def test_topic_body_only_on_explicit_request(self): + indexed = device_skills_handler({"device_type": "frr_vtysh"}, {})["skill"] + assert indexed["topics"]["bgp"] == "BGP" # index: names only, body withheld + + topic = device_skills_handler({"device_type": "frr_vtysh", "topic": "bgp"}, {})["skill"] + assert topic["topic"] == {"bgp": {"name": "BGP", "syntax": "router bgp "}} + + def test_unknown_key_lists_available(self): + # Not a key the list would return — the error carries the loaded + # keys anyway, so a stale caller can see what step 1 offers. + result = device_skills_handler({"device_type": "cisco_asa"}, {}) + assert result["status"] == "failed" + assert "Unknown device_type" in result["error"] + assert set(result["available_device_types"]) == set(FAKE_SKILLS) + + def test_missing_device_type(self): + result = device_skills_handler({"action": "get"}, {}) + assert result["status"] == "failed" + assert "Provide device_type" in result["error"] diff --git a/tests/agent/mcp/test_tool_params.py b/tests/agent/mcp/test_tool_params.py index b4c01d910..1dd47365e 100644 --- a/tests/agent/mcp/test_tool_params.py +++ b/tests/agent/mcp/test_tool_params.py @@ -105,6 +105,7 @@ HANDLER_FILES = { "device_config_send_handler": "device_config.py", "device_show_run_handler": "device_config.py", "vpcs_config_set_handler": "device_config.py", + "device_skills_handler": "skills.py", }