refactor(copilot): reuse MCP tools via a bridge; extract shared device runners

The copilot and the MCP service maintained two parallel wrapper layers
(LangChain BaseTool classes vs @mcp.tool() functions) over the same
handlers in gns3_client/api_handlers.py. Descriptions and parameters
drifted apart (compute_id and link_type were missing on the copilot
side). This makes the MCP registration the single source of truth and
removes the duplicated wrappers.

tools_v2/mcp_bridge.py adapts the MCP server's tool registration into
LangChain tools: names, descriptions and argument schemas come from the
MCP tools. The pool is filtered to project-scoped tools
(MCP_ALLOWED_TOOLS) because the copilot runs inside one open project —
project management, compute/appliance/image administration and server
info tools stay out. The bridge carries the copilot's request JWT into
the MCP contextvars (username/token_version decoded from the token so
ticket-minting tools work) and runs the async MCP functions from the
copilot's sync tool node on either thread flavor.

Mode toolsets (teaching / lab_automation / troubleshooting_injection)
are now composed from adapted MCP tools plus a few copilot-native ones
that add value the MCP versions lack: link_create (port-name
resolution), wait_seconds, packet_analysis(+skills), and the topology
reader. Eight orphaned LangChain wrappers are deleted.

The device command tools had the dependency inverted (the MCP handlers
instantiated the copilot LangChain classes and round-tripped through
JSON strings). The Nornir/Netmiko classes moved verbatim (git mv) into
the shared layer as plain runners — DeviceConfigCommandRunner,
DeviceShowCommandRunner, VpcsCommandRunner — with _run(json_string)
becoming run(params, gns3_ctx). The optional Jinja2 template rendering
moved from the MCP handlers into the runners (and into
utils/device_configs.render_device_template), so both entry paths get
it; the MCP handlers are now pure delegation. This also drops the
json.dumps/json.loads detour the MCP path used to take.

test_tool_params consistency gate extended: a handler that forwards the
whole params dict to a callee is a wildcard (same rationale as the
params.items() case) — the per-key check cannot see through delegation.
This commit is contained in:
YueGuobin committed 2026-11-03 22:04:57 +08:00
1 parent 9c27a293d0
commit 6a4cbe39c1
34 files changed
+986 -2772

No files matched your search

@@ -72,26 +72,14 @@ from gns3server.agent.gns3_copilot.gns3_client.context_helpers import (
get_current_llm_config,
)
from gns3server.agent.gns3_copilot.prompts import load_system_prompt
from gns3server.agent.gns3_copilot.skills import DeviceSkillsTool, InjectionSkillsTool, PacketAnalysisSkillsTool
from gns3server.agent.gns3_copilot.skills import PacketAnalysisSkillsTool
from gns3server.agent.gns3_copilot.skills.registry import get_prompt
from gns3server.agent.gns3_copilot.tools_v2 import (
ExecuteMultipleDeviceCommands,
ExecuteMultipleDeviceConfigCommands,
GNS3CreateEllipseDrawingTool,
GNS3CreateNodeTool,
GNS3CreateRectangleDrawingTool,
GNS3CreateTextDrawingTool,
GNS3LinkTool,
GNS3PacketFilterTool,
GNS3StartNodeTool,
GNS3StopNodeTool,
GNS3SuspendNodeTool,
GNS3TemplateTool,
GNS3UpdateNodeNameTool,
GNS3WaitTool,
PacketAnalysisTool,
adapted_mcp_tools,
)
from gns3server.agent.gns3_copilot.tools_v2.vpcs_tools_netmiko import VPCSCommands
# Set up logger for GNS3-Copilot
logger = logging.getLogger(__name__)
@@ -100,55 +88,83 @@ logger = logging.getLogger(__name__)
# system. The model_factory module handles model creation with configuration
# from the database.
# Define tools for different copilot modes
# Teaching assistant mode: READ-ONLY diagnostic tools only
# Define tools for different copilot modes.
#
# MCP-backed tools are adapted from the MCP server registration (single
# source of truth for names, descriptions and argument schemas — see
# tools_v2/mcp_bridge.py). Only project-scoped tools are eligible: the
# copilot runs inside one open project, so project management and server
# administration tools are filtered out by the bridge.
#
# Copilot-native tools remain where they add value over the MCP version:
# - GNS3LinkTool ("link_create"): resolves port NAMES to adapter/port
# numbers so the model does not need a node_get round-trip per link
# - GNS3WaitTool ("wait_seconds"): boot wait timer, pairs with node_start
# - PacketAnalysisTool/PacketAnalysisSkillsTool: tshark analysis, no MCP
# counterpart by design (server-side pcap analysis was rejected)
# - GNS3TopologyTool: aggregated nodes+links+ports view in one call
# Teaching assistant mode: READ-ONLY diagnostics plus topology building
TEACHING_ASSISTANT_MODE_TOOLS = [
GNS3TemplateTool(), # Get GNS3 node templates
GNS3CreateNodeTool(), # Create new nodes in GNS3
GNS3LinkTool(), # Create links between nodes
GNS3CreateTextDrawingTool(), # Add text labels to the canvas
GNS3CreateRectangleDrawingTool(), # Add rectangle annotations to the canvas
GNS3CreateEllipseDrawingTool(), # Add ellipse annotations to the canvas
GNS3StartNodeTool(), # Start GNS3 nodes (returns immediately)
GNS3WaitTool(), # Wait for nodes to boot (pair with start_gns3_node)
GNS3UpdateNodeNameTool(), # Update node name
ExecuteMultipleDeviceCommands(), # Execute show/display/debug commands
# (READ-ONLY)
PacketAnalysisTool(), # Protocol-oriented packet analysis with tshark
PacketAnalysisSkillsTool(), # Query packet analysis protocol definitions
DeviceSkillsTool(), # Get device-specific skills and command knowledge
*adapted_mcp_tools(
names=[
"template_list",
"template_get",
"node_create",
"node_update",
"drawing_create_text",
"drawing_create_rectangle",
"drawing_create_ellipse",
"node_start",
"device_show_run",
"device_skill_get",
]
),
GNS3LinkTool(), # native: port-name resolution
GNS3WaitTool(), # wait for nodes to boot (pairs with node_start)
PacketAnalysisTool(), # protocol-oriented packet analysis with tshark
PacketAnalysisSkillsTool(), # query packet analysis protocol definitions
]
# Lab automation assistant mode: Full diagnostic AND configuration tools
LAB_AUTOMATION_ASSISTANT_MODE_TOOLS = [
GNS3TemplateTool(), # Get GNS3 node templates
GNS3CreateNodeTool(), # Create new nodes in GNS3
GNS3LinkTool(), # Create links between nodes
GNS3CreateTextDrawingTool(), # Add text labels to the canvas
GNS3CreateRectangleDrawingTool(), # Add rectangle annotations to the canvas
GNS3CreateEllipseDrawingTool(), # Add ellipse annotations to the canvas
GNS3StartNodeTool(), # Start GNS3 nodes (returns immediately)
GNS3WaitTool(), # Wait for nodes to boot (pair with start_gns3_node)
GNS3StopNodeTool(), # Stop GNS3 nodes
GNS3SuspendNodeTool(), # Suspend GNS3 nodes (preserve state)
GNS3UpdateNodeNameTool(), # Update node name
ExecuteMultipleDeviceCommands(), # Execute show/display/debug commands
# (READ-ONLY)
ExecuteMultipleDeviceConfigCommands(), # Execute configuration commands
VPCSCommands(), # Execute VPCS commands using Netmiko
PacketAnalysisTool(), # Protocol-oriented packet analysis with tshark
PacketAnalysisSkillsTool(), # Query packet analysis protocol definitions
DeviceSkillsTool(), # Get device-specific skills and command knowledge
*adapted_mcp_tools(
names=[
"template_list",
"template_get",
"node_create",
"node_update",
"drawing_create_text",
"drawing_create_rectangle",
"drawing_create_ellipse",
"node_start",
"node_stop",
"node_suspend",
"device_show_run",
"device_config_send",
"vpcs_config_set",
"device_skill_get",
]
),
GNS3LinkTool(), # native: port-name resolution
GNS3WaitTool(), # wait for nodes to boot (pairs with node_start)
PacketAnalysisTool(), # protocol-oriented packet analysis with tshark
PacketAnalysisSkillsTool(), # query packet analysis protocol definitions
]
# Troubleshooting injection mode: Tools for injecting network faults
# Focused on configuration commands and injection skills for fault injection
TROUBLESHOOTING_INJECTION_MODE_TOOLS = [
ExecuteMultipleDeviceCommands(), # Get device configurations (READ-ONLY)
ExecuteMultipleDeviceConfigCommands(), # Inject configuration changes
GNS3PacketFilterTool(), # Manage packet filters on links (delay, loss, corrupt, etc.)
InjectionSkillsTool(), # Query injection skills and fault types
GNS3TopologyTool(), # Get topology information
*adapted_mcp_tools(
names=[
"device_show_run",
"device_config_send",
"link_update",
"link_available_filters",
"injection_skill_get",
]
),
GNS3TopologyTool(), # aggregated topology view (nodes + links + ports)
]
# Default tools (legacy support - will be overridden by mode-specific tools)
@@ -28,8 +28,8 @@ This module provides a tool to execute configuration commands on multiple
devices in a GNS3 topology using Nornir.
⚠️ WARNING: This module is shared with the MCP (Model Context Protocol) service.
ExecuteMultipleDeviceConfigCommands._run() is called by the MCP device_config_send handler.
The jwt_token/url parameters were added for MCP compatibility.
DeviceConfigCommandRunner.run() is called by the MCP device_config_send handler
and by the copilot through the MCP tool bridge.
Modifications must be tested with BOTH gns3-copilot AND MCP.
"""
@@ -38,8 +38,6 @@ import logging
import re
from typing import Any
from langchain.tools import BaseTool
from langchain_core.callbacks import CallbackManagerForToolRun
from netmiko.exceptions import ReadTimeout
from nornir import InitNornir
from nornir.core import Nornir
@@ -113,84 +111,57 @@ def _get_nornir_defaults() -> dict[str, Any]:
return {"data": {"location": "gns3"}}
class ExecuteMultipleDeviceConfigCommands(BaseTool):
class DeviceConfigCommandRunner:
"""
A tool to execute configuration commands on multiple devices in a GNS3
topology using Nornir.
This class uses Nornir to manage connections and execute configuration
commands on multiple devices concurrently.
Executes configuration commands on multiple devices in a GNS3 topology
using Nornir (one session per device, devices in parallel).
Shared implementation behind the MCP ``device_config_send`` tool; the
copilot reaches it through the MCP tool bridge. Not a LangChain tool —
the tool name/description contract lives in the MCP registration
(agent/mcp/__init__.py).
IMPORTANT SAFETY NOTE:
This tool is intended for configuration changes only. Use extreme caution
when executing configuration commands.
This runner is intended for configuration changes only. Use extreme
caution when executing configuration commands. Forbidden commands
(reload/erase/format/...) are filtered by
``utils.command_filter.filter_forbidden_commands``.
"""
name: str = "execute_multiple_device_config_commands"
description: str = """
Executes CONFIGURATION commands on multiple devices in the current GNS3
topology.
Use this tool ONLY for changing device settings (e.g., 'configure',
'interface', 'ip address', 'router ospf').
For viewing information, use the 'execute_multiple_device_commands' tool.
Input should be a JSON object containing project_id and device configs.
Example input:
{
"project_id": "<PROJECT_UUID>",
"device_configs": [
{
"device_name": "R-1",
"config_commands": [
"interface Loopback0",
"ip address 1.1.1.1 255.255.255.255",
"description CONFIG_BY_TOOL"
]
},
{
"device_name": "R-2",
"config_commands": [
"interface Loopback0",
"ip address 2.2.2.2 255.255.255.255",
"description CONFIG_BY_TOOL"
]
}
]
}
Returns a list of dicts with device name and config results.
IMPORTANT SAFETY WARNING:
Do NOT use this tool for dangerous operations that could reboot, erase,
or factory-reset devices.
Forbidden operations include but are not limited to:
- reload / reboot commands
- write erase / erase startup-config
- format / erase nvram / delete flash:
- boot system commands
- factory-reset commands
- any commands that require user confirmation prompts
- NEVER use 'exit' command - this disconnects the session and breaks subsequent commands
"""
def _run(
def run(
self,
tool_input: str, # or Union[str, List[Any], Dict[str, Any]]
run_manager: CallbackManagerForToolRun | None = None,
jwt_token: str | None = None,
url: str | None = None,
**kwargs: Any,
params: dict[str, Any] | str,
gns3_ctx: dict[str, Any] | None = None,
) -> list[dict[str, Any]]:
"""
Executes configuration commands on multiple devices in GNS3 topology.
Args:
tool_input (str): A JSON string containing project_id and device
configuration commands to execute.
jwt_token: JWT token for GNS3 API auth (MCP handlers).
url: GNS3 server URL (MCP handlers).
params: ``{"project_id", "device_configs", "template"?}``.
A JSON string is accepted for backward compatibility.
``template`` is an optional Jinja2 template rendered with
each device's ``vars`` into ``config_commands``.
gns3_ctx: handler context with ``jwt_token`` / ``server_url``.
Returns:
List[Dict[str, Any]]: A list of dicts containing device names and
configuration results.
"""
jwt_token = (gns3_ctx or {}).get("jwt_token")
url = (gns3_ctx or {}).get("server_url")
# Optional Jinja2 template: render per-device vars into config_commands
if isinstance(params, dict) and params.get("template"):
from gns3server.agent.gns3_copilot.utils.device_configs import render_device_template
rendered = render_device_template(
params["template"], params.get("device_configs", []), commands_field="config_commands"
)
if len(rendered) == 1 and "error" in rendered[0]:
return rendered
params = {**params, "device_configs": rendered}
tool_input = params
# Log received input
logger.debug("Received input: %s", tool_input)
@@ -711,12 +682,12 @@ if __name__ == "__main__":
}
)
exe_config = ExecuteMultipleDeviceConfigCommands()
exe_config = DeviceConfigCommandRunner()
failed_count = 0
for _i in range(0, 5):
exe_results = exe_config._run(tool_input=input_paras)
exe_results = exe_config.run(params=input_paras)
for result in exe_results:
for result in exe_results:
if result.get("status") == "failed":
@@ -28,8 +28,8 @@ This module provides a tool to execute display commands on multiple devices
in a GNS3 topology using Nornir.
⚠️ WARNING: This module is shared with the MCP (Model Context Protocol) service.
ExecuteMultipleDeviceCommands._run() is called by the MCP device_command_run handler.
The jwt_token/url parameters were added for MCP compatibility.
DeviceShowCommandRunner.run() is called by the MCP device_show_run handler
and by the copilot through the MCP tool bridge.
Modifications must be tested with BOTH gns3-copilot AND MCP.
"""
@@ -38,8 +38,6 @@ import logging
import re
from typing import Any
from langchain.tools import BaseTool
from langchain_core.callbacks import CallbackManagerForToolRun
from netmiko.exceptions import ReadTimeout
from nornir import InitNornir
from nornir.core import Nornir
@@ -113,14 +111,16 @@ def _get_nornir_defaults() -> dict[str, Any]:
return {"data": {"location": "gns3"}}
class ExecuteMultipleDeviceCommands(BaseTool):
class DeviceShowCommandRunner:
"""
A READ-ONLY diagnostic tool for viewing network device configurations.
A READ-ONLY diagnostic runner for viewing network device configurations.
**CRITICAL: DIAGNOSIS ONLY - NO CONFIGURATION PERMISSIONS**
This tool is exclusively designed for read-only operations to inspect and
diagnose network devices. It CANNOT and MUST NOT be used for configuration.
Shared implementation behind the MCP ``device_show_run`` tool; the
copilot reaches it through the MCP tool bridge. Not a LangChain tool —
the tool name/description contract lives in the MCP registration
(agent/mcp/__init__.py).
**Allowed Command Types:**
- Display commands: show, display (Cisco/Huawei)
@@ -135,50 +135,10 @@ class ExecuteMultipleDeviceCommands(BaseTool):
- Any command that modifies device state
"""
name: str = "execute_multiple_device_commands"
description: str = """
**READ-ONLY DIAGNOSTIC TOOL** - View network device configurations.
Use this tool to inspect device information without making any changes.
**PERMITTED USE CASES:**
- View device status: show version, show running-config
- Check routing: show ip route, show ip ospf neighbor, show bgp summary
- Interface status: show ip interface brief, show interfaces
- Protocol diagnostics: show ospf database, show bgp routes, debug commands
- Connectivity testing: ping, traceroute
**STRICTLY FORBIDDEN:**
- NO configuration commands (configure terminal, interface, router, etc.)
- NO commands that modify device state
- NEVER use 'exit' command - this disconnects the session and breaks subsequent commands
- If you need to configure, provide guidance to the student instead
**Input Format:**
{
"project_id": "<PROJECT_UUID>",
"device_configs": [
{
"device_name": "R-1",
"commands": ["show version", "show ip interface brief"]
},
{
"device_name": "R-2",
"commands": ["show version", "show ip ospf neighbor"]
}
]
}
**Returns:** List of device outputs for diagnostic analysis.
"""
def _run(
def run(
self,
tool_input: str | bytes | list[Any] | dict[str, Any],
run_manager: CallbackManagerForToolRun | None = None,
jwt_token: str | None = None,
url: str | None = None,
**kwargs: Any,
params: dict[str, Any] | str,
gns3_ctx: dict[str, Any] | None = None,
) -> list[dict[str, Any]]:
"""
Executes READ-ONLY diagnostic commands on multiple devices in GNS3.
@@ -187,13 +147,30 @@ class ExecuteMultipleDeviceCommands(BaseTool):
configuration changes to network devices.
Args:
tool_input: JSON string with project_id and diagnostic commands.
jwt_token: JWT token for GNS3 API auth (MCP handlers).
url: GNS3 server URL (MCP handlers).
params: ``{"project_id", "device_configs", "template"?}``.
A JSON string is accepted for backward compatibility.
``template`` is an optional Jinja2 template rendered with
each device's ``vars`` into ``commands``.
gns3_ctx: handler context with ``jwt_token`` / ``server_url``.
Returns:
List[Dict]: A list of dicts with device names and outputs.
"""
jwt_token = (gns3_ctx or {}).get("jwt_token")
url = (gns3_ctx or {}).get("server_url")
# Optional Jinja2 template: render per-device vars into commands
if isinstance(params, dict) and params.get("template"):
from gns3server.agent.gns3_copilot.utils.device_configs import render_device_template
rendered = render_device_template(
params["template"], params.get("device_configs", []), commands_field="commands"
)
if len(rendered) == 1 and "error" in rendered[0]:
return rendered
params = {**params, "device_configs": rendered}
tool_input = params
# Log received input
logger.debug("Received input: %s", tool_input)
@@ -648,12 +625,12 @@ if __name__ == "__main__":
}
)
exe_cmd = ExecuteMultipleDeviceCommands()
exe_cmd = DeviceShowCommandRunner()
failed_count = 0
for _i in range(0, 1):
exe_results = exe_cmd._run(tool_input=device_commands)
exe_results = exe_cmd.run(params=device_commands)
for result in exe_results:
for result in exe_results:
if result.get("status") == "failed":
@@ -28,8 +28,8 @@ This module provides a tool to execute commands on VPCS devices
in a GNS3 topology using Nornir with Netmiko.
⚠️ WARNING: This module is shared with the MCP (Model Context Protocol) service.
VPCSCommands._run() is called by the MCP vpcs_config_set handler.
The jwt_token/url parameters were added for MCP compatibility.
VpcsCommandRunner.run() is called by the MCP vpcs_config_set handler
and by the copilot through the MCP tool bridge.
Modifications must be tested with BOTH gns3-copilot AND MCP.
"""
@@ -38,8 +38,6 @@ import logging
import re
from typing import Any
from langchain.tools import BaseTool
from langchain_core.callbacks import CallbackManagerForToolRun
from netmiko.exceptions import ReadTimeout
from nornir import InitNornir
from nornir.core import Nornir
@@ -98,15 +96,17 @@ def _get_nornir_defaults() -> dict[str, Any]:
return {"data": {"location": "gns3"}}
class VPCSCommands(BaseTool):
class VpcsCommandRunner:
"""
A tool for VPCS (Virtual PC Simulator) devices.
Runs commands on VPCS (Virtual PC Simulator) devices in a GNS3 topology.
**VPCS-SPECIFIC TOOL** - This tool ONLY works with VPCS virtual PC devices.
**VPCS-SPECIFIC RUNNER** - This runner ONLY works with VPCS virtual PC
devices.
**IMPORTANT DISTINCTION:**
Unlike network devices (routers/switches), VPCS devices are lightweight virtual PCs.
Commands like 'ip' are basic PC IP config, NOT network device config.
Shared implementation behind the MCP ``vpcs_config_set`` tool; the
copilot reaches it through the MCP tool bridge. Not a LangChain tool —
the tool name/description contract lives in the MCP registration
(agent/mcp/__init__.py).
**Allowed VPCS Commands:**
- IP configuration: ip <address>/<mask> <gateway>
@@ -117,63 +117,26 @@ class VPCSCommands(BaseTool):
- Save/Load: save, load
"""
name: str = "execute_vpcs_commands"
description: str = """
**VPCS VIRTUAL PC TOOL** - Configure and test Virtual PC Simulator devices.
This tool ONLY works with VPCS devices, NOT routers/switches.
**IMPORTANT: VPCS vs Network Devices**
- VPCS = Lightweight virtual PCs for lab testing (NOT network infra)
- 'ip' command on VPCS = Basic PC IP config (like 'ipconfig' on Windows)
- NOT the same as configuring router interfaces or routing protocols
**When to Use This Tool:**
- Configure IP addresses on virtual PCs: ip 10.10.0.12/24 10.10.0.254
- Test connectivity from PCs: ping 10.10.0.254
- View PC IP configuration: ip, show ip
- Display ARP table: arp
- Check PC version: version
**Input Format:**
{
"project_id": "<PROJECT_UUID>",
"device_configs": [
{
"device_name": "PC1",
"commands": ["ip", "ping 10.10.0.254"]
},
{
"device_name": "PC2",
"commands": ["show ip"]
}
]
}
**Returns:** PC command outputs for IP config and connectivity testing.
**Note:** For network devices, use execute_multiple_device_commands.
"""
def _run(
def run(
self,
tool_input: str | bytes | list[Any] | dict[str, Any],
run_manager: CallbackManagerForToolRun | None = None,
jwt_token: str | None = None,
url: str | None = None,
**kwargs: Any,
params: dict[str, Any] | str,
gns3_ctx: dict[str, Any] | None = None,
) -> list[dict[str, Any]]:
"""
Execute commands on multiple VPCS devices in GNS3 topology.
Args:
tool_input: JSON string with project_id and VPCS commands.
jwt_token: JWT token for GNS3 API auth (MCP handlers).
url: GNS3 server URL (MCP handlers).
params: ``{"project_id", "device_configs"}``. A JSON string is
accepted for backward compatibility.
gns3_ctx: handler context with ``jwt_token`` / ``server_url``.
Returns:
List of dicts with device names and command outputs.
"""
jwt_token = (gns3_ctx or {}).get("jwt_token")
url = (gns3_ctx or {}).get("server_url")
tool_input = params
# Log received input
logger.debug("Received input: %s", tool_input)
@@ -625,7 +588,7 @@ if __name__ == "__main__":
}
)
exe_cmd = VPCSCommands()
result = exe_cmd._run(tool_input=command_groups)
exe_cmd = VpcsCommandRunner()
result = exe_cmd.run(params=command_groups)
print("Execution results:")
print(json.dumps(result, indent=2, ensure_ascii=False))
@@ -22,53 +22,36 @@
#
# Project Home: https://github.com/yueguobin/gns3-copilot
#
"""
"""
GNS3-Copilot Tools Package
This package provides various tools for interacting with GNS3 network simulator:
- Device configuration command execution
- Display command execution
- Multiple device command execution using Nornir
- VPCS device configuration using Netmiko
- Node and link management
- Packet filter management
Most copilot tools are now adapted from the MCP server registration via
``mcp_bridge.adapted_mcp_tools()`` — the MCP tools are the single source
of truth for names, descriptions and argument schemas (see
``mcp_bridge.MCP_ALLOWED_TOOLS`` for the project-scoped filter).
Main modules:
- config_tools_nornir: Multiple device configuration command execution tool using Nornir
- display_tools_nornir: Multiple device command execution tool using Nornir
- vpcs_tools_netmiko: VPCS device configuration tool using Netmiko
- gns3_create_node: GNS3 node creation tool
- gns3_create_link: GNS3 link creation tool
- gns3_create_drawing: GNS3 canvas drawing tools (text, rectangle, ellipse)
- gns3_start_node: GNS3 node startup tool (immediate return, no boot wait)
- gns3_wait: Wait timer tool (pair with node start to let devices boot)
- gns3_get_node_temp: GNS3 template retrieval tool
- gns3_update_node_name: GNS3 node name update tool
- gns3_packet_filter: GNS3 packet filter management tool
This package keeps only the copilot-native tools that add behavior the
MCP counterparts lack:
Note: GNS3TopologyTool is now available from gns3_client package
- gns3_create_link: link creation with port-NAME resolution ("link_create";
shadows the adapted MCP tool of the same name)
- gns3_wait: boot wait timer ("wait_seconds"; pairs with node_start)
- packet_analysis_tool: server-side tshark pcap analysis ("packet_analysis";
no MCP counterpart by design)
The Nornir/Netmiko device command runners live in the shared layer as
plain classes (gns3_client/device_config_commands.py, device_show_commands.py,
vpcs_commands.py) behind the MCP device_config_send / device_show_run /
vpcs_config_set tools, which the copilot uses through the bridge.
Author: Yue Guobin (岳国宾)
"""
# Import main tool classes
from .config_tools_nornir import ExecuteMultipleDeviceConfigCommands
from .display_tools_nornir import ExecuteMultipleDeviceCommands
from .gns3_create_drawing import (
GNS3CreateEllipseDrawingTool,
GNS3CreateRectangleDrawingTool,
GNS3CreateTextDrawingTool,
)
from .gns3_create_link import GNS3LinkTool
from .gns3_create_node import GNS3CreateNodeTool
from .gns3_get_node_temp import GNS3TemplateTool
from .gns3_packet_filter import GNS3PacketFilterTool
from .gns3_start_node import GNS3StartNodeQuickTool, GNS3StartNodeTool
from .gns3_stop_node import GNS3StopNodeTool
from .gns3_suspend_node import GNS3SuspendNodeTool
from .gns3_update_node_name import GNS3UpdateNodeNameTool
from .gns3_wait import GNS3WaitTool
from .mcp_bridge import adapted_mcp_tools
from .packet_analysis_tool import PacketAnalysisTool
# Dynamic version management
@@ -83,25 +66,10 @@ __author__ = "Yue Guobin (岳国宾)"
__description__ = "AI-powered network automation assistant for GNS3"
__url__ = "https://github.com/yueguobin/gns3-copilot"
# Export main tool classes
# Export main tool classes and the MCP bridge
__all__ = [
"ExecuteMultipleDeviceCommands",
"ExecuteMultipleDeviceConfigCommands",
"GNS3CreateEllipseDrawingTool",
"GNS3CreateNodeTool",
"GNS3CreateRectangleDrawingTool",
"GNS3CreateTextDrawingTool",
"GNS3LinkTool",
"GNS3PacketFilterTool",
"GNS3StartNodeQuickTool",
"GNS3StartNodeTool",
"GNS3StopNodeTool",
"GNS3SuspendNodeTool",
"GNS3TemplateTool",
"GNS3UpdateNodeNameTool",
"GNS3WaitTool",
"PacketAnalysisTool",
"adapted_mcp_tools",
]
# Package initialization message
# print(f"GNS3-Copilot Tools package loaded (version {__version__})")
@@ -1,162 +0,0 @@
# SPDX-License-Identifier: GPL-3.0-or-later
#
# GNS3-Copilot - AI-powered Network Lab Assistant for GNS3
#
# This file is part of GNS3-Copilot project.
#
# GNS3-Copilot 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.
#
# GNS3-Copilot 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 GNS3-Copilot. If not, see <https://www.gnu.org/licenses/>.
#
# Copyright (C) 2025 Yue Guobin (岳国宾)
# Author: Yue Guobin (岳国宾)
#
# Project Home: https://github.com/yueguobin/gns3-copilot
#
"""
GNS3 canvas drawing tools for text, rectangle and ellipse annotations.
Thin LangChain wrappers over the shared REST handlers in
``gns3_client.api_handlers``; the Web UI compatible SVG is assembled and
validated by ``gns3server.utils.drawings`` (single implementation shared
with the MCP drawing tools).
"""
import json
import logging
from typing import Any
from langchain.tools import BaseTool
from langchain_core.callbacks import CallbackManagerForToolRun
from gns3server.agent.gns3_copilot.gns3_client.api_handlers import (
build_gns3_ctx,
create_ellipse_drawing_handler,
create_rectangle_drawing_handler,
create_text_drawing_handler,
)
# Configure logging
logger = logging.getLogger(__name__)
class _GNS3CreateDrawingToolBase(BaseTool):
"""Shared plumbing: parse JSON input, build ctx, dispatch to a handler."""
def _dispatch(self, input_data: dict[str, Any], gns3_ctx: dict[str, Any]) -> dict[str, Any]:
raise NotImplementedError
def _run(
self,
tool_input: str,
run_manager: CallbackManagerForToolRun | None = None,
) -> dict[str, Any]:
try:
input_data = json.loads(tool_input)
gns3_ctx = build_gns3_ctx()
if gns3_ctx is None:
logger.error("Failed to create GNS3 connector")
return {"error": "Failed to connect to GNS3 server. Please check your configuration."}
return self._dispatch(input_data, gns3_ctx)
except json.JSONDecodeError as e:
logger.error("Invalid JSON input: %s", e)
return {"error": f"Invalid JSON input: {e}"}
except Exception as e:
logger.exception("Drawing creation failed")
return {"error": str(e)}
class GNS3CreateTextDrawingTool(_GNS3CreateDrawingToolBase):
"""
A LangChain tool to add a text label to the GNS3 project canvas.
**Input**:
A JSON object with project_id, x, y (top-left corner on the canvas)
and text; optional font_size (1-200, default 13), color (#RRGGBB,
default #000000), bold (default false), font_family (default
monospace) and z (default 1, keeps text above links).
Newlines in text start additional lines; XML characters are escaped
automatically; the computed width/height are returned.
**Output**:
A dictionary with the created drawing, its drawing_id and the
computed width/height/line_height, or an "error" key on failure.
"""
name: str = "drawing_create_text"
description: str = """
Adds a text label to the GNS3 project canvas.
Input: JSON with project_id, x, y (top-left corner), text and optional
font_size, color, bold, font_family, z.
Returns: the created drawing with its computed width and height.
"""
def _dispatch(self, input_data: dict[str, Any], gns3_ctx: dict[str, Any]) -> dict[str, Any]:
return create_text_drawing_handler(input_data, gns3_ctx)
class GNS3CreateRectangleDrawingTool(_GNS3CreateDrawingToolBase):
"""
A LangChain tool to add a rectangle to the GNS3 project canvas.
**Input**:
A JSON object with project_id, x, y (top-left corner), width and
height (1-2000); optional fill (#RRGGBB or "none", default #FFFFFF),
fill_opacity (0-1, default 1.0), stroke (#RRGGBB, no border by
default), stroke_width (1-20), dashed (bool), dasharray (like "4,2",
requires stroke) and rx (corner radius, default 0). z defaults to 0
so shapes stay behind nodes and text.
**Output**:
A dictionary with the created drawing, or an "error" key on failure.
"""
name: str = "drawing_create_rectangle"
description: str = """
Adds a rectangle to the GNS3 project canvas.
Input: JSON with project_id, x, y, width, height and optional fill,
fill_opacity, stroke, stroke_width, dashed, dasharray, rx, z.
Returns: the created drawing with its width and height.
"""
def _dispatch(self, input_data: dict[str, Any], gns3_ctx: dict[str, Any]) -> dict[str, Any]:
return create_rectangle_drawing_handler(input_data, gns3_ctx)
class GNS3CreateEllipseDrawingTool(_GNS3CreateDrawingToolBase):
"""
A LangChain tool to add an ellipse (or circle) to the GNS3 canvas.
**Input**:
A JSON object with project_id, x, y (bounding box top-left corner),
width and height (2-2000, equal values give a circle); the same
optional style fields as the rectangle tool. cx/cy are derived from
the bounding box; for odd width/height the drawing is 1 px smaller
than requested and the actual size is returned.
**Output**:
A dictionary with the created drawing, or an "error" key on failure.
"""
name: str = "drawing_create_ellipse"
description: str = """
Adds an ellipse or circle to the GNS3 project canvas.
Input: JSON with project_id, x, y, width, height (bounding box) and
optional fill, fill_opacity, stroke, stroke_width, dashed, dasharray, z.
Returns: the created drawing with its actual width and height.
"""
def _dispatch(self, input_data: dict[str, Any], gns3_ctx: dict[str, Any]) -> dict[str, Any]:
return create_ellipse_drawing_handler(input_data, gns3_ctx)
@@ -1,318 +0,0 @@
# SPDX-License-Identifier: GPL-3.0-or-later
#
# GNS3-Copilot - AI-powered Network Lab Assistant for GNS3
#
# This file is part of GNS3-Copilot project.
#
# GNS3-Copilot 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.
#
# GNS3-Copilot 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 GNS3-Copilot. If not, see <https://www.gnu.org/licenses/>.
#
# Copyright (C) 2025 Yue Guobin (岳国宾)
# Author: Yue Guobin (岳国宾)
#
# Project Home: https://github.com/yueguobin/gns3-copilot
#
"""
GNS3 node creation tool for network topology building.
Provides functionality to create multiple nodes in GNS3 projects
using specified templates and coordinates through the GNS3 API.
"""
import json
import logging
from pprint import pprint
from typing import Any
from langchain.tools import BaseTool
from langchain_core.callbacks import CallbackManagerForToolRun
from gns3server.agent.gns3_copilot.gns3_client.api_handlers import (
build_gns3_ctx,
create_node_handler,
)
# Configure logging
logger = logging.getLogger(__name__)
class GNS3CreateNodeTool(BaseTool):
"""
A LangChain tool to create multiple nodes in a GNS3 project
using specified templates and coordinates.
**Input:**
A JSON object with project_id and array of nodes with template_id,
x, y coordinates, and optional name.
Example input:
{
"project_id": "uuid-of-project",
"nodes": [
{
"template_id": "uuid-of-template",
"x": 100,
"y": -200,
"name": "R1"
},
{
"template_id": "uuid-of-template2",
"x": -200,
"y": 300,
"name": "R2"
}
]
}
**Output:**
A dictionary containing the creation results for all nodes.
Example output:
{
"project_id": "uuid-of-project",
"created_nodes": [
{
"node_id": "uuid-of-node1",
"name": "R1",
"status": "success"
},
{
"node_id": "uuid-of-node2",
"name": "R2",
"status": "success"
}
],
"total_nodes": 2,
"successful_nodes": 2,
"failed_nodes": 0
}
If error occurs during validation, returns dict with error message.
"""
name: str = "node_create"
description: str = """
Creates multiple nodes in a GNS3 project using templates and coordinates.
Input is a JSON object with project_id and array of nodes.
Each node requires: template_id, x, y. Optional: name (to set node name directly),
compute_id (compute to place the node on, default "local").
Example input:
{
"project_id": "uuid-of-project",
"nodes": [
{
"template_id": "uuid-of-template",
"x": 100,
"y": -200,
"name": "R1"
},
{
"template_id": "uuid-of-template2",
"x": -200,
"y": 300,
"name": "R2",
"compute_id": "uuid-of-remote-compute"
}
]
}
IMPORTANT: Ensure distance between any two nodes is greater than 250 px.
This spacing is necessary to display interface numbers clearly for better
topology visualization.
Returns a dictionary with creation results for all nodes, including
success/failure status.
If the operation fails during input validation, returns a dictionary with
an error message.
"""
def _run(
self,
tool_input: str,
run_manager: CallbackManagerForToolRun | None = None,
**kwargs: Any,
) -> dict[str, Any]:
"""
Creates nodes in a GNS3 project with templates and coordinates.
Args:
tool_input: A JSON string with project_id and an array of nodes.
run_manager: LangChain run manager (unused).
Returns:
dict: A dictionary with creation results for all nodes or an error
message.
"""
# Log received input
logger.info("Received input: %s", tool_input)
try:
# Parse input JSON
input_data = json.loads(tool_input)
project_id = input_data.get("project_id")
nodes = input_data.get("nodes", [])
# Validate input
if not project_id:
logger.error("Invalid input: Missing project_id.")
return {"error": "Missing project_id."}
if not isinstance(nodes, list) or len(nodes) == 0:
logger.error("Invalid input: nodes must be a non-empty array.")
return {"error": "nodes must be a non-empty array."}
# Validate each node in the array
for i, node_data in enumerate(nodes):
if not isinstance(node_data, dict):
logger.error("Invalid input: Node %d must be a dictionary.", i + 1)
return {"error": f"Node {i + 1} must be a dictionary."}
template_id = node_data.get("template_id")
x = node_data.get("x")
y = node_data.get("y")
name = node_data.get("name")
compute_id = node_data.get("compute_id")
if not all(
[
template_id,
isinstance(x, (int, float)),
isinstance(y, (int, float)),
]
):
logger.error(
"Invalid input: Node %d missing or invalid template_id, x, or y.",
i + 1,
)
return {"error": f"Node {i + 1} missing or invalid template_id, x, or y."}
# Build handler context (JWT + server URL from request context)
logger.info("Connecting to GNS3 server...")
gns3_ctx = build_gns3_ctx()
if gns3_ctx is None:
logger.error("Failed to create GNS3 connector")
return {"error": "Failed to connect to GNS3 server. Please check your configuration."}
# Create nodes
logger.info("Creating %d nodes in project %s...", len(nodes), project_id)
results: list[dict[str, Any]] = []
for i, node_data in enumerate(nodes):
try:
template_id = node_data.get("template_id")
x = node_data.get("x")
y = node_data.get("y")
name = node_data.get("name")
compute_id = node_data.get("compute_id")
logger.info(
"Creating node %d/%d with template %s at (%s, %s), name=%s...",
i + 1,
len(nodes),
template_id,
x,
y,
name,
)
# Create node via the shared REST handler. compute_id is
# passed only when set — the handler defaults to "local".
node_params: dict[str, Any] = {
"project_id": project_id,
"template_id": template_id,
"x": x,
"y": y,
}
if name:
node_params["name"] = name
if compute_id:
node_params["compute_id"] = compute_id
created = create_node_handler(node_params, gns3_ctx)
if isinstance(created, list):
raise RuntimeError("Unexpected batch response when creating a single node")
if "error" in created:
raise RuntimeError(created["error"])
node_info = {
"node_id": created.get("node_id"),
"name": created.get("name"),
"status": "success",
}
results.append(node_info)
except Exception as e:
error_info = {
"error": f"Node {i + 1} creation failed: {e!s}",
"status": "failed",
}
results.append(error_info)
logger.error("Failed to create node %d: %s", i + 1, e)
# Continue with next node even if one fails
# Calculate summary statistics
successful_nodes = len([r for r in results if r.get("status") == "success"])
failed_nodes = len([r for r in results if r.get("status") == "failed"])
# Prepare final result
final_result = {
"project_id": project_id,
"created_nodes": results,
"total_nodes": len(nodes),
"successful_nodes": successful_nodes,
"failed_nodes": failed_nodes,
}
# Log the final result
logger.info(
"Node creation completed: %d successful, %d failed, %d total.",
successful_nodes,
failed_nodes,
len(nodes),
)
# Return JSON-formatted result
return final_result
except json.JSONDecodeError as e:
logger.error("Invalid JSON input: %s", e)
return {"error": f"Invalid JSON input: {e}"}
except Exception as e:
logger.error("Failed to process node creation request: %s", e)
return {"error": f"Failed to process node creation request: {e!s}"}
if __name__ == "__main__":
# Test the tool locally with multiple nodes
test_input = json.dumps(
{
# TODO: Replace with actual project UUID
"project_id": "d7fc094c-685e-4db1-ac11-5e33a1b2e066",
"nodes": [
{
# TODO: Replace with actual template UUID
"template_id": "b923a635-b7cc-4cb5-9a86-9357e04c02f7",
"x": 100,
"y": -200,
"name": "R1",
},
{
# TODO: Replace with actual template UUID
"template_id": "b923a635-b7cc-4cb5-9a86-9357e04c02f7",
"x": 200,
"y": -300,
"name": "R2",
},
],
}
)
tool = GNS3CreateNodeTool()
result = tool._run(test_input)
pprint(result)
@@ -1,178 +0,0 @@
# SPDX-License-Identifier: GPL-3.0-or-later
#
# GNS3-Copilot - AI-powered Network Lab Assistant for GNS3
#
# This file is part of GNS3-Copilot project.
#
# GNS3-Copilot 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.
#
# GNS3-Copilot 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 GNS3-Copilot. If not, see <https://www.gnu.org/licenses/>.
#
# Copyright (C) 2025 Yue Guobin (岳国宾)
# Author: Yue Guobin (岳国宾)
#
# Project Home: https://github.com/yueguobin/gns3-copilot
#
"""
GNS3 template retrieval tool for device discovery.
Provides functionality to retrieve all available device templates
from a GNS3 server, including template names, IDs, and types.
Filters out built-in utility templates that are not useful for network labs.
"""
import json
import logging
from pprint import pprint
from typing import Any
from langchain.tools import BaseTool
from langchain_core.callbacks import CallbackManagerForToolRun
from gns3server.agent.gns3_copilot.gns3_client import get_gns3_connector
# Configure logging
logger = logging.getLogger(__name__)
# Built-in templates to filter out (utility templates, not actual network devices)
FILTERED_TEMPLATES = {
"atm_switch", # ATM switch
"cloud", # Cloud
"ethernet_hub", # Ethernet hub
"ethernet_switch", # Ethernet switch (built-in)
"frame_relay_switch", # Frame Relay switch
"nat", # NAT device
}
def should_filter_template(template: dict[str, Any]) -> bool:
"""
Determine whether a template should be filtered out.
Filter condition:
1. Template type is in the filter list (exact match)
Args:
template: Template dictionary
Returns:
True if template should be filtered, False if it should be kept
"""
template_type = template.get("template_type", "")
# Check if template_type is in filter list
# This is the most reliable way to identify built-in utility templates
return template_type in FILTERED_TEMPLATES
class GNS3TemplateTool(BaseTool):
"""
LangChain tool to retrieve available device templates from GNS3 server.
Connects to GNS3 server and extracts name, template_id, and template_type.
Filters out built-in utility templates that are not useful for network labs.
**Input:**
No input required. Connects to GNS3 server at default URL.
**Output:**
Dict with list of dicts (name, template_id, template_type).
If error, returns dict with error message.
**Filtered Templates:**
The following built-in utility templates are excluded:
- ATM switch
- Cloud
- Ethernet hub
- Ethernet switch (built-in)
- Frame Relay switch
- NAT
"""
name: str = "get_gns3_templates"
description: str = """
Retrieves available device templates from GNS3 server for network labs.
Returns dict with list of dicts (name, template_id, template_type).
Filters out built-in utility templates (ATM switch, Cloud, Ethernet hub,
Ethernet switch, Frame Relay switch, NAT) as they are not useful for
network device configuration.
No input required.
If connection fails, returns dict with error message.
"""
def _run(
self,
tool_input: str = "",
run_manager: CallbackManagerForToolRun | None = None,
) -> dict[str, Any]:
"""
Connects to GNS3 server and retrieves available device templates.
Args:
tool_input: Optional input (not used).
run_manager: LangChain run manager (unused).
Returns:
dict: Dict with templates list or error message.
"""
try:
# Initialize Gns3Connector using factory function
logger.info("Connecting to GNS3 server...")
gns3_server = get_gns3_connector()
if gns3_server is None:
logger.error("Failed to create GNS3 connector")
return {"error": ("Failed to connect to GNS3 server. Please check your configuration.")}
# Retrieve all available templates
templates = gns3_server.http_call("get", f"{gns3_server.base_url}/templates").json()
# Filter out utility templates and extract relevant info
template_info = []
filtered_count = 0
for template in templates:
# Check if template should be filtered
if should_filter_template(template):
filtered_count += 1
logger.debug("Filtered out template: %s", template.get("name"))
continue
# Extract name, template_id, and template_type
template_info.append(
{
"name": template.get("name", "N/A"),
"template_id": template.get("template_id", "N/A"),
"template_type": template.get("template_type", "N/A"),
}
)
# Return JSON-formatted result with full logging
result = {"templates": template_info}
logger.info(
"Template retrieval completed. Total: %d, Filtered: %d, Remaining: %d",
len(templates),
filtered_count,
len(template_info),
)
logger.debug("Result: %s", json.dumps(result, indent=2, ensure_ascii=False))
return result
except Exception as e:
logger.error("Failed to connect to GNS3 server or retrieve templates: %s", e)
return {"error": f"Failed to retrieve templates: {e!s}"}
if __name__ == "__main__":
# Test's tool locally
tool = GNS3TemplateTool()
result = tool._run("")
pprint(result)
@@ -1,488 +0,0 @@
# SPDX-License-Identifier: GPL-3.0-or-later
#
# GNS3-Copilot - AI-powered Network Lab Assistant for GNS3
#
# This file is part of GNS3-Copilot project.
#
# GNS3-Copilot 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.
#
# GNS3-Copilot 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 GNS3-Copilot. If not, see <https://www.gnu.org/licenses/>.
#
# Copyright (C) 2025 Yue Guobin (岳国宾)
# Author: Yue Guobin (岳国宾)
#
# Project Home: https://github.com/yueguobin/gns3-copilot
#
"""
GNS3 packet filter management tool for network simulation.
Provides functionality to manage packet filters on GNS3 links,
including latency, packet loss, corruption, and BPF filtering.
"""
import json
import logging
import subprocess
from pprint import pprint
from typing import Any
from langchain.tools import BaseTool
from langchain_core.callbacks import CallbackManagerForToolRun
from gns3server.agent.gns3_copilot.gns3_client.api_handlers import (
available_filters_handler,
build_gns3_ctx,
get_link_handler,
update_link_handler,
)
# Configure logging
logger = logging.getLogger(__name__)
class GNS3PacketFilterTool(BaseTool):
"""
A LangChain tool to manage packet filters on GNS3 links.
Supports getting available filters, setting filters, and clearing filters
on network links to simulate various network conditions.
**Input:**
A JSON object with project_id, link_id, action, and optional filter parameters.
Note: show_filters_icon is automatically set to false by default to hide the filter
icon in the GNS3 Web UI.
Example input for getting available filters:
{
"project_id": "uuid-of-project",
"link_id": "uuid-of-link",
"action": "get_available"
}
Example input for setting filters:
{
"project_id": "uuid-of-project",
"link_id": "uuid-of-link",
"action": "set",
"filters": {
"delay": [100, 10],
"packet_loss": [5]
},
"show_filters_icon": false
}
Example input for getting current filters:
{
"project_id": "uuid-of-project",
"link_id": "uuid-of-link",
"action": "get"
}
Example input for clearing filters:
{
"project_id": "uuid-of-project",
"link_id": "uuid-of-link",
"action": "clear"
}
**Output:**
A dictionary containing the action result.
For "get_available": returns list of available filter types
For "set": returns updated link information with applied filters
For "get": returns current filters configured on the link
For "clear": returns confirmation that filters were cleared
"""
name: str = "manage_gns3_packet_filter"
description: str = """
Manages packet filters on GNS3 links to inject network faults and simulate network conditions.
This tool is primarily used for fault injection scenarios to create realistic network problems
for troubleshooting practice, such as latency, packet loss, and corruption.
By default, the filter icon in the GNS3 Web UI is hidden (show_filters_icon=false) to avoid
visual clutter when injecting faults for troubleshooting exercises.
Supported actions:
- "get_available": Get list of available filter types for the link
- "set": Set packet filters on the link to inject network faults
- "get": Get current filters configured on the link
Common filter types for fault injection:
- "frequency_drop": Drop every Nth packet (parameter: frequency, -1 to 32767)
- "packet_loss": Packet loss percentage (parameters: chance 0-100, optional correlation)
- "delay": Delay in ms with optional jitter and distribution (parameters: latency 0-32767,
jitter 0-32767, distribution uniform|normal|pareto|paretonormal)
- "corrupt": Packet corruption percentage (parameter: chance, 0-100)
- "bpf": Berkeley Packet Filter (parameter: filter expression text)
- "rate": Bandwidth cap, tc-style string like "512kbit" (kernel links only)
- "reorder": Packet reordering (parameters: percentage, correlation, gap; needs delay;
kernel links only)
- "gemodel": Gilbert-Elliot bursty loss (parameters: p good-to-bad transition, r bad-to-good
transition, 1-h loss in the bad state; mean loss = p/(p+r)*(1-h); kernel links only)
- "duplicate": Packet duplication percentage (kernel links only)
- "seed": Reproducible netem random draws (kernel links only; needs kernel >= 6.6 -
older kernels silently ignore the seed)
- "limit": Impairment queue depth in packets (kernel links only)
- "quota": Byte cap — after the quota, drop with a chance (parameters: bytes, chance;
kernel links only)
- "window_drop": Time-window outage (parameters: start_ms, outage_ms, chance, optional
period_ms, jitter_ms; start is relative to when the filter is applied — any filter
update restarts the schedule; kernel links only)
Filter availability depends on the link (kernel-only types need kernel-datapath links
and compute support): always check with action "get_available" before setting.
Input is a JSON object with:
- project_id (str): GNS3 project UUID
- link_id (str): GNS3 link UUID
- action (str): One of "get_available", "set", "get", "clear"
- filters (dict, optional): Filter configuration for "set" action
Example for getting available filters:
{
"project_id": "uuid-of-project",
"link_id": "uuid-of-link",
"action": "get_available"
}
Example for setting delay and packet loss:
{
"project_id": "uuid-of-project",
"link_id": "uuid-of-link",
"action": "set",
"filters": {
"delay": [100, 10],
"packet_loss": [5]
}
}
Returns a dictionary with action result, filter information, or error message.
"""
def _run(
self,
tool_input: str,
run_manager: CallbackManagerForToolRun | None = None,
**kwargs: Any,
) -> dict[str, Any]:
"""
Manages packet filters on a GNS3 link.
Args:
tool_input: A JSON string with project_id, link_id, action, and optional filters.
run_manager: LangChain run manager (unused).
Returns:
dict: A dictionary with action result or an error message.
"""
# Log received input
logger.info("Received input: %s", tool_input)
try:
# Parse input JSON
input_data = json.loads(tool_input)
project_id = input_data.get("project_id")
link_id = input_data.get("link_id")
action = input_data.get("action")
show_filters_icon = input_data.get("show_filters_icon", False)
# Validate required fields
if not project_id:
logger.error("Invalid input: Missing project_id.")
return {"error": "Missing project_id."}
if not link_id:
logger.error("Invalid input: Missing link_id.")
return {"error": "Missing link_id."}
if not action:
logger.error("Invalid input: Missing action.")
return {"error": "Missing action."}
# Validate action
valid_actions = ["get_available", "set", "get", "clear"]
if action not in valid_actions:
logger.error("Invalid action: %s. Must be one of %s", action, valid_actions)
return {"error": f"Invalid action: {action}. Must be one of {valid_actions}"}
# Validate filters for "set" action
if action == "set":
filters = input_data.get("filters")
if not filters or not isinstance(filters, dict):
logger.error("Invalid input: 'set' action requires 'filters' dict.")
return {"error": "'set' action requires 'filters' dict with filter configuration."}
# Build handler context (JWT + server URL from request context)
logger.info("Connecting to GNS3 server...")
gns3_ctx = build_gns3_ctx()
if gns3_ctx is None:
logger.error("Failed to create GNS3 connector")
return {"error": "Failed to connect to GNS3 server. Please check your configuration."}
# Execute action
logger.info("Processing packet filter action '%s' for link %s...", action, link_id)
if action == "get_available":
result = self._get_available_filters(gns3_ctx, project_id, link_id)
elif action == "set":
filters = input_data.get("filters", {})
result = self._set_filters(gns3_ctx, project_id, link_id, filters, show_filters_icon)
elif action == "get":
result = self._get_filters(gns3_ctx, project_id, link_id)
elif action == "clear":
result = self._clear_filters(gns3_ctx, project_id, link_id, show_filters_icon)
else:
result = {"error": f"Unknown action: {action}"}
# Log result
logger.info("Packet filter action '%s' completed successfully.", action)
return result
except json.JSONDecodeError as e:
logger.error("Invalid JSON input: %s", e)
return {"error": f"Invalid JSON input: {e}"}
except Exception as e:
logger.error("Failed to process packet filter request: %s", e)
return {"error": f"Failed to process packet filter request: {e!s}"}
def _get_available_filters(self, gns3_ctx: dict, project_id: str, link_id: str) -> dict[str, Any]:
"""Get available filter types for the link."""
try:
filters = available_filters_handler({"project_id": project_id, "link_id": link_id}, gns3_ctx)
if "error" in filters:
raise RuntimeError(filters["error"])
logger.info("Retrieved %d available filter types.", len(filters))
return {
"action": "get_available",
"link_id": link_id,
"available_filters": filters,
"count": len(filters),
"status": "success",
}
except Exception as e:
logger.error("Failed to get available filters: %s", e)
return {
"action": "get_available",
"link_id": link_id,
"error": f"Failed to get available filters: {e!s}",
"status": "failed",
}
def _validate_bpf_syntax(self, bpf_expression: str) -> dict[str, Any]:
"""
Validate BPF filter expression syntax using tshark.
Args:
bpf_expression: BPF filter expression to validate
Returns:
dict with 'valid' (bool) and 'error' (str or None) keys
"""
try:
# Use tshark to validate BPF syntax with 1 second timeout
# Use -i lo (loopback) to avoid "(null)" interface in error messages
result = subprocess.run(
["tshark", "-f", bpf_expression, "-i", "lo"],
timeout=1,
capture_output=True,
text=True,
)
# Check if output contains "Invalid" indicating syntax error
if "Invalid" in result.stdout or "Invalid" in result.stderr:
error_lines: list[str] = []
if "Invalid" in result.stderr:
error_lines.extend(line for line in result.stderr.split("\n") if "Invalid" in line)
if "Invalid" in result.stdout:
error_lines.extend(line for line in result.stdout.split("\n") if "Invalid" in line)
# Strip interface suffix (e.g., "for interface 'lo'") for cleaner error
error_msg_parts = []
for line in error_lines:
clean = line.split(" for interface")[0].strip()
if clean:
error_msg_parts.append(clean)
error_msg = " ".join(error_msg_parts) if error_msg_parts else "Invalid BPF syntax"
logger.warning("BPF syntax validation failed: %s", error_msg)
return {"valid": False, "error": error_msg}
logger.info("BPF syntax validation passed")
return {"valid": True, "error": None}
except subprocess.TimeoutExpired:
# Timeout is expected behavior - tshark waits for traffic
# No "Invalid" in output means syntax is correct
logger.info("BPF syntax validation passed (timeout expected)")
return {"valid": True, "error": None}
except FileNotFoundError:
# tshark not installed - skip validation
logger.warning("tshark not found, skipping BPF syntax validation. Install tshark to enable BPF validation.")
return {"valid": True, "error": None}
except Exception as e:
logger.error("Unexpected error during BPF validation: %s", e)
return {"valid": False, "error": f"BPF validation error: {e!s}"}
def _set_filters(
self,
gns3_ctx: dict,
project_id: str,
link_id: str,
filters: dict[str, Any],
show_filters_icon: bool = False,
) -> dict[str, Any]:
"""Set packet filters on the link."""
try:
# Validate BPF syntax if BPF filter is present
if "bpf" in filters:
bpf_filters = filters["bpf"]
if isinstance(bpf_filters, list):
# Validate each BPF expression
for idx, bpf_expr in enumerate(bpf_filters):
if isinstance(bpf_expr, str):
validation = self._validate_bpf_syntax(bpf_expr)
if not validation["valid"]:
return {
"action": "set",
"link_id": link_id,
"error": f"BPF syntax error at index {idx}: {validation['error']}",
"status": "failed",
}
elif isinstance(bpf_filters, str):
# Single BPF expression
validation = self._validate_bpf_syntax(bpf_filters)
if not validation["valid"]:
return {
"action": "set",
"link_id": link_id,
"error": f"BPF syntax error: {validation['error']}",
"status": "failed",
}
# Update filters — the PUT response is the updated link
updated = update_link_handler(
{
"project_id": project_id,
"link_id": link_id,
"kwargs": {
"filters": filters,
"show_filters_icon": show_filters_icon,
},
},
gns3_ctx,
)
if "error" in updated:
raise RuntimeError(updated["error"])
logger.info("Successfully set filters on link %s", link_id)
return {
"action": "set",
"link_id": link_id,
"filters": updated.get("filters"),
"status": "success",
"message": "Filters applied successfully",
}
except Exception as e:
logger.error("Failed to set filters: %s", e)
return {
"action": "set",
"link_id": link_id,
"error": f"Failed to set filters: {e!s}",
"status": "failed",
}
def _get_filters(self, gns3_ctx: dict, project_id: str, link_id: str) -> dict[str, Any]:
"""Get current filters configured on the link."""
try:
link = get_link_handler({"project_id": project_id, "link_id": link_id}, gns3_ctx)
if "error" in link:
raise RuntimeError(link["error"])
logger.info("Retrieved current filters for link %s", link_id)
return {
"action": "get",
"link_id": link_id,
"filters": link.get("filters"),
"status": "success",
}
except Exception as e:
logger.error("Failed to get filters: %s", e)
return {
"action": "get",
"link_id": link_id,
"error": f"Failed to get filters: {e!s}",
"status": "failed",
}
def _clear_filters(
self,
gns3_ctx: dict,
project_id: str,
link_id: str,
show_filters_icon: bool = False,
) -> dict[str, Any]:
"""Clear all filters from the link."""
try:
# Clear filters by setting an empty dict — the PUT response
# is the updated link
updated = update_link_handler(
{
"project_id": project_id,
"link_id": link_id,
"kwargs": {
"filters": {},
"show_filters_icon": show_filters_icon,
},
},
gns3_ctx,
)
if "error" in updated:
raise RuntimeError(updated["error"])
logger.info("Successfully cleared filters on link %s", link_id)
return {
"action": "clear",
"link_id": link_id,
"filters": updated.get("filters"),
"status": "success",
"message": "Filters cleared successfully",
}
except Exception as e:
logger.error("Failed to clear filters: %s", e)
return {
"action": "clear",
"link_id": link_id,
"error": f"Failed to clear filters: {e!s}",
"status": "failed",
}
if __name__ == "__main__":
# Test the tool locally
# TODO: Replace with actual project and link UUIDs
test_input = json.dumps(
{
"project_id": "d7fc094c-685e-4db1-ac11-5e33a1b2e066",
"link_id": "link-uuid-here",
"action": "get_available",
}
)
tool = GNS3PacketFilterTool()
result = tool._run(test_input)
pprint(result)
@@ -1,242 +0,0 @@
# SPDX-License-Identifier: GPL-3.0-or-later
#
# GNS3-Copilot - AI-powered Network Lab Assistant for GNS3
#
# This file is part of GNS3-Copilot project.
#
# GNS3-Copilot 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.
#
# GNS3-Copilot 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 GNS3-Copilot. If not, see <https://www.gnu.org/licenses/>.
#
# Copyright (C) 2025 Yue Guobin (岳国宾)
# Author: Yue Guobin (岳国宾)
#
# Project Home: https://github.com/yueguobin/gns3-copilot
#
"""
GNS3 node startup tool for network device activation.
Sends start commands and returns immediately — it never blocks on a fixed
boot timer. A failed start command (e.g. a 409 from the compute) is
reported in the same round-trip instead of after a two-minute progress
bar. Use the wait_seconds tool between this and any status check to give
nodes time to boot.
"""
import json
import logging
from pprint import pprint
from typing import Any
from langchain.tools import BaseTool
from langchain_core.callbacks import CallbackManagerForToolRun
from gns3server.agent.gns3_copilot.gns3_client.api_handlers import (
build_gns3_ctx,
get_nodes_handler,
start_node_handler,
)
# Configure logging
logger = logging.getLogger(__name__)
class GNS3StartNodeTool(BaseTool):
"""
A LangChain tool to start one or multiple nodes in a GNS3 project.
Sends the start commands in a parallel batch and returns each node's
status immediately — nodes keep booting in the background. It does NOT
wait for boot completion: follow up with the wait_seconds tool and a
status/topology check to confirm nodes actually came up.
**Input**:
A JSON object with project_id and node_ids (list of node IDs).
Example:
{
"project_id": "uuid-of-project",
"node_ids": ["uuid-of-node-1", "uuid-of-node-2"]
}
**Output**:
A dict with nodes' details immediately after sending start commands:
{
"project_id": "...",
"total_nodes": 2,
"successful": 2,
"failed": 0,
"nodes": [
{"node_id": "...", "name": "...", "status": "started"},
{"node_id": "...", "name": "...", "status": "error", "error": "..."}
],
"note": "Start commands sent. Nodes are booting in background."
}
"""
name: str = "start_gns3_node"
description: str = """
Starts one or multiple nodes in a GNS3 project and returns immediately
(nodes boot in the background; start failures are reported right away).
After calling this, use wait_seconds (VPCS/IOU ~15-30s, IOS routers
~60-120s, heavy NOS images 2-5min) before checking node status.
Input: JSON with project_id and node_ids (list of node IDs).
Returns: Dict with per-node start command results.
"""
def _run(
self,
tool_input: str,
run_manager: CallbackManagerForToolRun | None = None,
) -> dict[str, Any]:
try:
# Parse input JSON
input_data = json.loads(tool_input)
project_id = input_data.get("project_id")
node_ids = input_data.get("node_ids")
# Validate input
if not project_id or not node_ids:
logger.error("Missing required fields: project_id or node_ids.")
return {"error": "Missing required fields: project_id and node_ids."}
if not isinstance(node_ids, list):
logger.error("node_ids must be a list.")
return {"error": "node_ids must be a list."}
# Build handler context (JWT + server URL from request context)
logger.info("Connecting to GNS3 server...")
gns3_ctx = build_gns3_ctx()
if gns3_ctx is None:
logger.error("Failed to create GNS3 connector")
return {"error": "Failed to connect to GNS3 server. Please check your configuration."}
# Verify nodes exist and capture pre-start info (one call)
listing = get_nodes_handler({"project_id": project_id}, gns3_ctx)
if "error" in listing:
return {"error": listing["error"]}
nodes_by_id = {n["node_id"]: n for n in listing["nodes"]}
# Send start commands for all nodes (parallel batch)
logger.info(
"Sending start commands for %d nodes in project %s...",
len(node_ids),
project_id,
)
results = []
known_ids = [nid for nid in node_ids if nid in nodes_by_id]
start_results = start_node_handler({"project_id": project_id, "node_ids": known_ids}, gns3_ctx)
start_errors = (
{r["node_id"]: r.get("error") for r in start_results if r.get("status") == "error"}
if isinstance(start_results, list)
else {}
)
# Get immediate status (likely 'starting' or 'stopped') — one call
listing = get_nodes_handler({"project_id": project_id}, gns3_ctx)
if "error" in listing:
return {"error": listing["error"]}
after_by_id = {n["node_id"]: n for n in listing["nodes"]}
for node_id in node_ids:
if node_id not in nodes_by_id:
logger.error("Node %s not found in project %s", node_id, project_id)
results.append(
{
"node_id": node_id,
"name": "N/A",
"status": "error",
"error": "Node not found",
}
)
continue
if node_id in start_errors:
logger.error(
"Failed to start node %s: %s",
node_id,
start_errors[node_id],
)
results.append(
{
"node_id": node_id,
"name": nodes_by_id[node_id].get("name") or "N/A",
"status": "error",
"error": start_errors[node_id],
}
)
continue
logger.info(
"Start command sent for node %s (%s)",
node_id,
nodes_by_id[node_id].get("name"),
)
current = after_by_id.get(node_id, nodes_by_id[node_id])
results.append(
{
"node_id": node_id,
"name": current.get("name") or "N/A",
"status": current.get("status") or "unknown",
}
)
# Analyze results (count based on successful command sending)
successful_nodes = [r for r in results if r.get("status") != "error"]
failed_nodes = [r for r in results if r.get("status") == "error"]
# Construct final response
response = {
"project_id": project_id,
"total_nodes": len(node_ids),
"successful": len(successful_nodes),
"failed": len(failed_nodes),
"nodes": results,
"note": (
"Start commands sent. Nodes are booting in background. Use wait_seconds, then check node status."
),
}
logger.info(
"Quick start commands sent: %d successful, %d failed",
len(successful_nodes),
len(failed_nodes),
)
return response
except json.JSONDecodeError as e:
logger.error("Invalid JSON input: %s", e)
return {"error": f"Invalid JSON input: {e}"}
except Exception as e:
logger.error("Failed to start nodes: %s", e)
return {"error": f"Failed to start nodes: {e!s}"}
# Backward-compat alias: the waiting variant was removed; both names now
# point at the immediate-return tool.
GNS3StartNodeQuickTool = GNS3StartNodeTool
if __name__ == "__main__":
# Test with single node
print("=== Testing single node startup ===")
test_input_single = json.dumps(
{
"project_id": "<PROJECT_UUID>", # Replace with actual project UUID
"node_ids": ["fbeda109-9a74-4d8c-a749-cc3847911a90"], # Replace with actual node UUID
}
)
tool = GNS3StartNodeTool()
result_single = tool._run(test_input_single)
pprint(result_single)
@@ -1,231 +0,0 @@
# SPDX-License-Identifier: GPL-3.0-or-later
#
# GNS3-Copilot - AI-powered Network Lab Assistant for GNS3
#
# This file is part of GNS3-Copilot project.
#
# GNS3-Copilot 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.
#
# GNS3-Copilot 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 GNS3-Copilot. If not, see <https://www.gnu.org/licenses/>.
#
# Copyright (C) 2025 Yue Guobin (岳国宾)
# Author: Yue Guobin (岳国宾)
#
# Project Home: https://github.com/yueguobin/gns3-copilot
#
"""
GNS3 node stop tool for network device shutdown.
Provides functionality to stop one or multiple nodes in GNS3 projects.
"""
import json
import logging
from pprint import pprint
from typing import Any
from langchain.tools import BaseTool
from langchain_core.callbacks import CallbackManagerForToolRun
from gns3server.agent.gns3_copilot.gns3_client.api_handlers import (
build_gns3_ctx,
get_nodes_handler,
stop_node_handler,
)
# Configure logging
logger = logging.getLogger(__name__)
class GNS3StopNodeTool(BaseTool):
"""
A LangChain tool to stop one or multiple nodes in a GNS3 project.
**Input**:
A JSON object with project_id and node_ids (list of node IDs).
Example:
{
"project_id": "uuid-of-project",
"node_ids": ["uuid-of-node-1", "uuid-of-node-2"]
}
**Output**:
A dictionary with all nodes' details:
{
"project_id": "...",
"total_nodes": 2,
"successful": 2,
"failed": 0,
"nodes": [
{"node_id": "...", "name": "...", "status": "stopped"},
{"node_id": "...", "name": "...", "status": "stopped"}
]
}
"""
name: str = "stop_gns3_node"
description: str = """
Stops one or multiple nodes in a GNS3 project.
Input: JSON with project_id and node_ids (list of node IDs).
Returns: A dict with all nodes' details (success/failure status).
"""
def _run(
self,
tool_input: str,
run_manager: CallbackManagerForToolRun | None = None,
) -> dict[str, Any]:
try:
# Parse input JSON
input_data = json.loads(tool_input)
project_id = input_data.get("project_id")
node_ids = input_data.get("node_ids")
# Validate input
if not project_id or not node_ids:
logger.error("Missing required fields: project_id or node_ids.")
return {"error": "Missing required fields: project_id and node_ids."}
if not isinstance(node_ids, list):
logger.error("node_ids must be a list.")
return {"error": "node_ids must be a list."}
# Build handler context (JWT + server URL from request context)
logger.info("Connecting to GNS3 server...")
gns3_ctx = build_gns3_ctx()
if gns3_ctx is None:
logger.error("Failed to create GNS3 connector")
return {"error": "Failed to connect to GNS3 server. Please check your configuration."}
# Verify nodes exist and capture names (one call)
listing = get_nodes_handler({"project_id": project_id}, gns3_ctx)
if "error" in listing:
return {"error": listing["error"]}
nodes_by_id = {n["node_id"]: n for n in listing["nodes"]}
# Stop all nodes (parallel batch) and collect results
logger.info(
"Stopping %d nodes in project %s...",
len(node_ids),
project_id,
)
results = []
known_ids = [nid for nid in node_ids if nid in nodes_by_id]
stop_results = stop_node_handler({"project_id": project_id, "node_ids": known_ids}, gns3_ctx)
stop_errors = (
{r["node_id"]: r.get("error") for r in stop_results if r.get("status") == "error"}
if isinstance(stop_results, list)
else {}
)
# Get updated status — one call
listing = get_nodes_handler({"project_id": project_id}, gns3_ctx)
if "error" in listing:
return {"error": listing["error"]}
after_by_id = {n["node_id"]: n for n in listing["nodes"]}
for node_id in node_ids:
if node_id not in nodes_by_id:
logger.error("Node %s not found in project %s", node_id, project_id)
results.append(
{
"node_id": node_id,
"name": "N/A",
"status": "error",
"error": "Node not found",
}
)
elif node_id in stop_errors:
logger.error("Failed to stop node %s: %s", node_id, stop_errors[node_id])
results.append(
{
"node_id": node_id,
"name": nodes_by_id[node_id].get("name") or "N/A",
"status": "error",
"error": stop_errors[node_id],
}
)
else:
logger.info(
"Stop command sent for node %s (%s)",
node_id,
nodes_by_id[node_id].get("name"),
)
current = after_by_id.get(node_id, nodes_by_id[node_id])
results.append(
{
"node_id": node_id,
"name": current.get("name") or "N/A",
"status": current.get("status") or "unknown",
}
)
# Analyze results
successful_nodes = [r for r in results if r.get("status") != "error"]
failed_nodes = [r for r in results if r.get("status") == "error"]
# Construct final response
response = {
"project_id": project_id,
"total_nodes": len(node_ids),
"successful": len(successful_nodes),
"failed": len(failed_nodes),
"nodes": results,
}
logger.info(
"Stop operation completed: %d successful, %d failed",
len(successful_nodes),
len(failed_nodes),
)
return response
except json.JSONDecodeError as e:
logger.error("Invalid JSON input: %s", e)
return {"error": f"Invalid JSON input: {e}"}
except Exception as e:
logger.error("Failed to stop nodes: %s", e)
return {"error": f"Failed to stop nodes: {e!s}"}
if __name__ == "__main__":
# Test with single node
print("=== Testing single node stop ===")
test_input_single = json.dumps(
{
"project_id": "<PROJECT_UUID>", # Replace with actual project UUID
"node_ids": ["fbeda109-9a74-4d8c-a749-cc3847911a90"], # Replace with actual node UUID
}
)
tool = GNS3StopNodeTool()
result_single = tool._run(test_input_single)
pprint(result_single)
# Test with multiple nodes
print("\n=== Testing multiple nodes stop ===")
test_input_multiple = json.dumps(
{
"project_id": "<PROJECT_UUID>", # Replace with actual project UUID
"node_ids": [
"fbeda109-9a74-4d8c-a749-cc3847911a90",
# Replace with actual node UUIDs
"another-node-uuid-here",
"third-node-uuid-here",
],
}
)
result_multiple = tool._run(test_input_multiple)
pprint(result_multiple)
@@ -1,242 +0,0 @@
# SPDX-License-Identifier: GPL-3.0-or-later
#
# GNS3-Copilot - AI-powered Network Lab Assistant for GNS3
#
# This file is part of GNS3-Copilot project.
#
# GNS3-Copilot 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.
#
# GNS3-Copilot 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 GNS3-Copilot. If not, see <https://www.gnu.org/licenses/>.
#
# Copyright (C) 2025 Yue Guobin (岳国宾)
# Author: Yue Guobin (岳国宾)
#
# Project Home: https://github.com/yueguobin/gns3-copilot
#
"""
GNS3 node suspend tool for pausing network devices.
Provides functionality to suspend one or multiple nodes in GNS3 projects.
Suspended nodes preserve their state in memory and can be quickly resumed.
"""
import json
import logging
from pprint import pprint
from typing import Any
from langchain.tools import BaseTool
from langchain_core.callbacks import CallbackManagerForToolRun
from gns3server.agent.gns3_copilot.gns3_client.api_handlers import (
build_gns3_ctx,
get_nodes_handler,
suspend_node_handler,
)
# Configure logging
logger = logging.getLogger(__name__)
class GNS3SuspendNodeTool(BaseTool):
"""
A LangChain tool to suspend one or multiple nodes in a GNS3 project.
**Input**:
A JSON object with project_id and node_ids (list of node IDs).
Example:
{
"project_id": "uuid-of-project",
"node_ids": ["uuid-of-node-1", "uuid-of-node-2"]
}
**Output**:
A dictionary with all nodes' details:
{
"project_id": "...",
"total_nodes": 2,
"successful": 2,
"failed": 0,
"nodes": [
{"node_id": "...", "name": "...", "status": "suspended"},
{"node_id": "...", "name": "...", "status": "suspended"}
]
}
**Note**: Suspended nodes preserve their state in memory and can be quickly
resumed. Use this when you want to pause a lab and continue later.
"""
name: str = "suspend_gns3_node"
description: str = """
Suspends one or multiple nodes in a GNS3 project.
Suspended nodes preserve their state and can be quickly resumed.
Use this to pause a lab temporarily and continue later.
Input: JSON with project_id and node_ids (list of node IDs).
Returns: A dict with all nodes' details (success/failure status).
"""
def _run(
self,
tool_input: str,
run_manager: CallbackManagerForToolRun | None = None,
) -> dict[str, Any]:
try:
# Parse input JSON
input_data = json.loads(tool_input)
project_id = input_data.get("project_id")
node_ids = input_data.get("node_ids")
# Validate input
if not project_id or not node_ids:
logger.error("Missing required fields: project_id or node_ids.")
return {"error": "Missing required fields: project_id and node_ids."}
if not isinstance(node_ids, list):
logger.error("node_ids must be a list.")
return {"error": "node_ids must be a list."}
# Build handler context (JWT + server URL from request context)
logger.info("Connecting to GNS3 server...")
gns3_ctx = build_gns3_ctx()
if gns3_ctx is None:
logger.error("Failed to create GNS3 connector")
return {"error": "Failed to connect to GNS3 server. Please check your configuration."}
# Verify nodes exist and capture names (one call)
listing = get_nodes_handler({"project_id": project_id}, gns3_ctx)
if "error" in listing:
return {"error": listing["error"]}
nodes_by_id = {n["node_id"]: n for n in listing["nodes"]}
# Suspend all nodes (parallel batch) and collect results
logger.info(
"Suspending %d nodes in project %s...",
len(node_ids),
project_id,
)
results = []
known_ids = [nid for nid in node_ids if nid in nodes_by_id]
suspend_results = suspend_node_handler({"project_id": project_id, "node_ids": known_ids}, gns3_ctx)
suspend_errors = (
{r["node_id"]: r.get("error") for r in suspend_results if r.get("status") == "error"}
if isinstance(suspend_results, list)
else {}
)
# Get updated status — one call
listing = get_nodes_handler({"project_id": project_id}, gns3_ctx)
if "error" in listing:
return {"error": listing["error"]}
after_by_id = {n["node_id"]: n for n in listing["nodes"]}
for node_id in node_ids:
if node_id not in nodes_by_id:
logger.error("Node %s not found in project %s", node_id, project_id)
results.append(
{
"node_id": node_id,
"name": "N/A",
"status": "error",
"error": "Node not found",
}
)
elif node_id in suspend_errors:
logger.error(
"Failed to suspend node %s: %s",
node_id,
suspend_errors[node_id],
)
results.append(
{
"node_id": node_id,
"name": nodes_by_id[node_id].get("name") or "N/A",
"status": "error",
"error": suspend_errors[node_id],
}
)
else:
logger.info(
"Suspend command sent for node %s (%s)",
node_id,
nodes_by_id[node_id].get("name"),
)
current = after_by_id.get(node_id, nodes_by_id[node_id])
results.append(
{
"node_id": node_id,
"name": current.get("name") or "N/A",
"status": current.get("status") or "unknown",
}
)
# Analyze results
successful_nodes = [r for r in results if r.get("status") != "error"]
failed_nodes = [r for r in results if r.get("status") == "error"]
# Construct final response
response = {
"project_id": project_id,
"total_nodes": len(node_ids),
"successful": len(successful_nodes),
"failed": len(failed_nodes),
"nodes": results,
"note": ("Suspended nodes preserve their state in memory. Use resume to continue where you left off."),
}
logger.info(
"Suspend operation completed: %d successful, %d failed",
len(successful_nodes),
len(failed_nodes),
)
return response
except json.JSONDecodeError as e:
logger.error("Invalid JSON input: %s", e)
return {"error": f"Invalid JSON input: {e}"}
except Exception as e:
logger.error("Failed to suspend nodes: %s", e)
return {"error": f"Failed to suspend nodes: {e!s}"}
if __name__ == "__main__":
# Test with single node
print("=== Testing single node suspend ===")
test_input_single = json.dumps(
{
"project_id": "<PROJECT_UUID>", # Replace with actual project UUID
"node_ids": ["fbeda109-9a74-4d8c-a749-cc3847911a90"], # Replace with actual node UUID
}
)
tool = GNS3SuspendNodeTool()
result_single = tool._run(test_input_single)
pprint(result_single)
# Test with multiple nodes
print("\n=== Testing multiple nodes suspend ===")
test_input_multiple = json.dumps(
{
"project_id": "<PROJECT_UUID>", # Replace with actual project UUID
"node_ids": [
"fbeda109-9a74-4d8c-a749-cc3847911a90",
# Replace with actual node UUIDs
"another-node-uuid-here",
"third-node-uuid-here",
],
}
)
result_multiple = tool._run(test_input_multiple)
pprint(result_multiple)
@@ -1,281 +0,0 @@
# SPDX-License-Identifier: GPL-3.0-or-later
#
# GNS3-Copilot - AI-powered Network Lab Assistant for GNS3
#
# This file is part of GNS3-Copilot project.
#
# GNS3-Copilot 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.
#
# GNS3-Copilot 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 GNS3-Copilot. If not, see <https://www.gnu.org/licenses/>.
#
# Copyright (C) 2025 Yue Guobin (岳国宾)
# Author: Yue Guobin (岳国宾)
#
# Project Home: https://github.com/yueguobin/gns3-copilot
#
"""
GNS3 node name update tool for renaming network devices.
Provides functionality to update the name of one or multiple nodes
in GNS3 projects.
"""
import json
import logging
from pprint import pprint
from typing import Any
from langchain.tools import BaseTool
from langchain_core.callbacks import CallbackManagerForToolRun
from gns3server.agent.gns3_copilot.gns3_client.api_handlers import (
build_gns3_ctx,
get_nodes_handler,
update_node_handler,
)
# Configure logging
logger = logging.getLogger(__name__)
class GNS3UpdateNodeNameTool(BaseTool):
"""
A LangChain tool to update the name of one or multiple nodes
in a GNS3 project.
**Input**:
A JSON object with project_id and nodes array containing
node_id and new_name.
Example:
{
"project_id": "uuid-of-project",
"nodes": [
{"node_id": "uuid-of-node-1", "new_name": "Router1"},
{"node_id": "uuid-of-node-2", "new_name": "Switch1"}
]
}
**Output**:
A dictionary with all nodes' update results:
{
"project_id": "...",
"total_nodes": 2,
"successful": 2,
"failed": 0,
"nodes": [
{
"node_id": "...",
"old_name": "...",
"new_name": "...",
"status": "success"
},
{
"node_id": "...",
"old_name": "...",
"new_name": "...",
"status": "success"
}
]
}
"""
name: str = "update_gns3_node_name"
description: str = """
Updates the name of one or multiple nodes in a GNS3 project.
Input: JSON with project_id and nodes array.
Each node must have node_id and new_name.
Returns: A dictionary with all nodes' update results
including success/failure status.
"""
def _run(
self,
tool_input: str,
run_manager: CallbackManagerForToolRun | None = None,
) -> dict[str, Any]:
try:
# Parse input JSON
input_data = json.loads(tool_input)
project_id = input_data.get("project_id")
nodes = input_data.get("nodes", [])
# Validate input
if not project_id:
logger.error("Missing required field: project_id.")
return {"error": "Missing required field: project_id."}
if not isinstance(nodes, list) or len(nodes) == 0:
logger.error("nodes must be a non-empty list.")
return {"error": "nodes must be a non-empty list."}
# Validate each node entry
for i, node_data in enumerate(nodes):
if not isinstance(node_data, dict):
logger.error("Node %d must be a dictionary.", i + 1)
return {"error": f"Node {i + 1} must be a dictionary."}
if "node_id" not in node_data or "new_name" not in node_data:
logger.error("Node %d missing node_id or new_name.", i + 1)
return {"error": f"Node {i + 1} missing node_id or new_name."}
# Build handler context (JWT + server URL from request context)
logger.info("Connecting to GNS3 server...")
gns3_ctx = build_gns3_ctx()
if gns3_ctx is None:
logger.error("Failed to create GNS3 connector")
return {"error": "Failed to connect to GNS3 server. Please check your configuration."}
# Fetch current node names in one call (old names + existence)
listing = get_nodes_handler({"project_id": project_id}, gns3_ctx)
if "error" in listing:
return {"error": listing["error"]}
nodes_by_id = {n["node_id"]: n for n in listing["nodes"]}
# Update node names
logger.info(
"Updating names for %d nodes in project %s...",
len(nodes),
project_id,
)
results = []
for i, node_data in enumerate(nodes):
try:
node_id = node_data.get("node_id")
new_name = node_data.get("new_name")
logger.info(
"Updating node %d/%d: %s -> %s",
i + 1,
len(nodes),
node_id,
new_name,
)
node = nodes_by_id.get(node_id)
if node is None:
raise ValueError("Node not found")
old_name = node.get("name")
# Update node name — the PUT response is the updated node
updated = update_node_handler(
{
"project_id": project_id,
"node_id": node_id,
"name": new_name,
},
gns3_ctx,
)
if "error" in updated:
raise RuntimeError(updated["error"])
current_name = updated.get("name")
if current_name == new_name:
node_info = {
"node_id": node_id,
"old_name": old_name,
"new_name": new_name,
"status": "success",
}
results.append(node_info)
logger.info(
"Successfully updated node name: %s -> %s",
old_name,
new_name,
)
else:
error_info = {
"node_id": node_id,
"old_name": old_name,
"new_name": new_name,
"current_name": current_name,
"status": "failed",
"error": "Name verification failed",
}
results.append(error_info)
logger.error("Failed to update node name for %s", node_id)
except Exception as e:
error_info = {
"node_id": node_data.get("node_id"),
"new_name": node_data.get("new_name"),
"status": "failed",
"error": str(e),
}
results.append(error_info)
logger.error("Failed to update node %d: %s", i + 1, e)
# Analyze results
successful_nodes = [r for r in results if r.get("status") == "success"]
failed_nodes = [r for r in results if r.get("status") == "failed"]
# Construct final response
response = {
"project_id": project_id,
"total_nodes": len(nodes),
"successful": len(successful_nodes),
"failed": len(failed_nodes),
"nodes": results,
}
logger.info(
"Name update completed: %d successful, %d failed",
len(successful_nodes),
len(failed_nodes),
)
return response
except json.JSONDecodeError as e:
logger.error("Invalid JSON input: %s", e)
return {"error": f"Invalid JSON input: {e}"}
except Exception as e:
logger.error("Failed to update node names: %s", e)
return {"error": f"Failed to update node names: {e!s}"}
if __name__ == "__main__":
# Test with single node
print("=== Testing single node name update ===")
test_input_single = json.dumps(
{
# Replace with actual project UUID
"project_id": "your-project-uuid",
"nodes": [
{
# Replace with actual node UUID
"node_id": "your-node-uuid",
"new_name": "Router1",
}
],
}
)
tool = GNS3UpdateNodeNameTool()
result_single = tool._run(test_input_single)
pprint(result_single)
# Test with multiple nodes
print("\n=== Testing multiple nodes name update ===")
test_input_multiple = json.dumps(
{
# Replace with actual project UUID
"project_id": "your-project-uuid",
"nodes": [
{"node_id": "node-uuid-1", "new_name": "Router1"},
{"node_id": "node-uuid-2", "new_name": "Switch1"},
{"node_id": "node-uuid-3", "new_name": "PC1"},
],
}
)
result_multiple = tool._run(test_input_multiple)
pprint(result_multiple)
@@ -26,10 +26,10 @@
GNS3-Copilot wait tool.
start_gns3_node returns as soon as the start commands are accepted — nodes
node_start returns as soon as the start commands are accepted — nodes
keep booting in the background. This tool gives the agent a deliberate
pause it controls itself (instead of a hard-coded progress bar inside the
start tool), so the usual flow is: start_gns3_node → wait_seconds → check
start tool), so the usual flow is: node_start → wait_seconds → check
node status / run show commands.
"""
@@ -67,7 +67,7 @@ class GNS3WaitTool(BaseTool):
name: str = "wait_seconds"
description: str = """
Pause execution for a given number of seconds (1-600), then continue.
Use after start_gns3_node (which returns immediately) to let nodes
Use after node_start (which returns immediately) to let nodes
boot before checking status: VPCS/IOU ~15-30s, IOS/IOL routers
~60-120s, heavy NOS images (XRd, SR Linux) 2-5min. Prefer several
short waits with a status check in between over one long blind wait.
@@ -0,0 +1,280 @@
# SPDX-License-Identifier: GPL-3.0-or-later
#
# GNS3-Copilot - AI-powered Network Lab Assistant for GNS3
#
# This file is part of GNS3-Copilot project.
#
# GNS3-Copilot 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.
#
# GNS3-Copilot 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 GNS3-Copilot. If not, see <https://www.gnu.org/licenses/>.
#
# Copyright (C) 2025 Yue Guobin (岳国宾)
# Author: Yue Guobin (岳国宾)
#
# Project Home: https://github.com/yueguobin/gns3-copilot
#
"""
Bridge that reuses the MCP server's tools inside the copilot agent.
The copilot and the MCP server used to maintain two parallel wrapper
layers (LangChain BaseTool classes vs @mcp.tool() functions) over the
same handlers in ``gns3_client.api_handlers`` — descriptions and
parameters drifted apart (compute_id and link_type were missing on the
copilot side for months). This bridge makes the MCP registration the
single source of truth: tool names, descriptions and argument schemas
are taken from the MCP server and wrapped into LangChain tools.
Scope: the copilot runs INSIDE one project, so project management and
server administration tools are filtered out (see MCP_ALLOWED_TOOLS).
``NATIVE_TOOL_NAMES`` lists the opposite case — copilot-native wrappers
that are richer than their MCP counterpart (link_create resolves port
names) and therefore shadow the adapted version.
Context bridging: the MCP tool functions read their JWT from contextvars
set by the MCP transport's auth wrapper. The copilot carries its own
request-scoped token, so the bridge sets those contextvars inside the
coroutine right before invoking the tool function (asyncio.to_thread
propagates the calling context, verified in agent/mcp/__init__.py).
"""
import asyncio
import json
import logging
from concurrent.futures import ThreadPoolExecutor
from typing import Any
from langchain_core.tools import BaseTool, StructuredTool
from pydantic import BaseModel, Field, create_model
from gns3server.agent.gns3_copilot.gns3_client.api_handlers import build_gns3_ctx
from gns3server.services import auth_service
logger = logging.getLogger(__name__)
# Project-scoped tools the copilot may use. Everything else the MCP server
# registers is server/project administration (project_*, template_create/
# update/delete, compute_*, appliance_*, image_*, server_*) and stays out
# because the copilot operates inside a single already-open project.
MCP_ALLOWED_TOOLS = frozenset(
{
# nodes
"node_list",
"node_get",
"node_start",
"node_stop",
"node_suspend",
"node_create",
"node_delete",
"node_update",
"node_duplicate",
"node_isolate",
"node_unisolate",
"node_links",
"node_start_all",
"node_stop_all",
"node_suspend_all",
"node_console_exec",
# node files
"node_file_list",
"node_file_get",
"node_file_write",
"node_file_delete",
# links
"link_list",
"link_get",
"link_delete",
"link_update",
"link_available_filters",
"link_reset",
"link_capture_start",
"link_capture_stop",
"link_capture_download",
"link_marker",
"marker_definition",
# drawings
"drawing_list",
"drawing_create_text",
"drawing_create_rectangle",
"drawing_create_ellipse",
"drawing_get",
"drawing_update",
"drawing_delete",
# snapshots
"snapshot_list",
"snapshot_create",
"snapshot_delete",
"snapshot_restore",
# templates (read-only; create/update/delete are admin tasks)
"template_list",
"template_get",
# device configuration
"device_config_send",
"device_show_run",
"vpcs_config_set",
# skills
"device_skill_get",
"injection_skill_get",
}
)
# Copilot-native wrappers that shadow their MCP namesake because they add
# value the MCP tool lacks (link_create accepts port NAMES and resolves
# them to adapter/port numbers). These names are never adapted.
NATIVE_TOOL_NAMES = frozenset({"link_create"})
_JSON_SCHEMA_TYPE_MAP = {
"string": str,
"integer": int,
"number": float,
"boolean": bool,
"array": list,
"object": dict,
}
# Cache of adapted tools keyed by MCP tool name — the MCP registration is
# immutable after import, so the wrap happens once per process.
_adapted_cache: dict[str, BaseTool] = {}
def _build_args_model(mcp_tool: Any) -> type[BaseModel]:
"""Build a pydantic args model from the MCP tool's JSON schema."""
schema = mcp_tool.parameters or {}
properties = schema.get("properties", {})
required = set(schema.get("required") or [])
fields: dict[str, Any] = {}
for param_name, param_spec in properties.items():
param_type = _JSON_SCHEMA_TYPE_MAP.get(param_spec.get("type"))
if param_type is None:
param_type = Any
description = param_spec.get("description")
if param_name in required:
fields[param_name] = (param_type, Field(..., description=description))
elif "default" in param_spec:
fields[param_name] = (param_type, Field(default=param_spec["default"], description=description))
else:
fields[param_name] = (param_type | None, Field(default=None, description=description))
return create_model(f"{mcp_tool.name}_args", **fields)
def _run_coro_sync(coro: Any) -> Any:
"""Run a coroutine to completion from synchronous code.
In a plain worker thread (no running loop) asyncio.run is enough.
When called from inside a running event loop (sync tool executed on
the loop thread), the coroutine runs on a fresh loop in a helper
thread; the contextvars are set inside the coroutine itself, so the
thread hop loses nothing.
"""
try:
asyncio.get_running_loop()
except RuntimeError:
return asyncio.run(coro)
with ThreadPoolExecutor(max_workers=1) as pool:
return pool.submit(asyncio.run, coro).result()
def _unwrap_mcp_content(raw: Any) -> Any:
"""Unwrap MCP content blocks ([{"type": "text", "text": ...}]) to plain data."""
if isinstance(raw, list) and raw and all(isinstance(block, dict) and block.get("type") == "text" for block in raw):
texts = [block.get("text", "") for block in raw]
if len(texts) == 1:
try:
return json.loads(texts[0])
except (json.JSONDecodeError, TypeError):
return texts[0]
return texts
return raw
def _invoke_mcp_tool(mcp_tool: Any, kwargs: dict[str, Any]) -> Any:
"""Invoke one MCP tool function with the copilot's credentials."""
ctx = build_gns3_ctx()
if ctx is None or not ctx.get("jwt_token"):
return {"error": "No GNS3 authentication token available in this request context."}
# Handlers that mint short-lived tickets (link_capture_download,
# node_console_exec) need the username and token_version; decode them
# from the copilot's own JWT. Handlers that do not need them tolerate
# the fallbacks.
username: str | None = None
token_version = 0
try:
token_data = auth_service.get_token_data(ctx["jwt_token"])
username = token_data.username
token_version = token_data.token_version
except Exception:
logger.debug("Could not decode the copilot JWT for username/token_version")
async def _call() -> Any:
# Set inside the coroutine: whatever thread/loop ends up running
# the handler thread inherits these via asyncio.to_thread's
# context copy (see _gns3_ctx in agent/mcp/__init__.py).
from gns3server.agent.mcp import _jwt_token_var, _jwt_token_version_var, _jwt_username_var
_jwt_token_var.set(ctx["jwt_token"])
_jwt_username_var.set(username)
_jwt_token_version_var.set(token_version)
return await mcp_tool.fn(**kwargs)
try:
raw = _run_coro_sync(_call())
except Exception as e:
logger.error("MCP tool %s failed via copilot bridge: %s", mcp_tool.name, e, exc_info=True)
return {"error": f"{type(e).__name__}: {e!s}"}
return _unwrap_mcp_content(raw)
def _adapt(mcp_tool: Any) -> BaseTool:
"""Wrap one MCP Tool into a LangChain StructuredTool."""
def _run(**kwargs: Any) -> Any:
return _invoke_mcp_tool(mcp_tool, kwargs)
return StructuredTool.from_function(
func=_run,
name=mcp_tool.name,
description=mcp_tool.description or "",
args_schema=_build_args_model(mcp_tool),
)
def adapted_mcp_tools(names: list[str] | None = None) -> list[BaseTool]:
"""Return LangChain tools adapted from the MCP server registration.
Args:
names: restrict to these MCP tool names (must also be allowed).
None means every allowed tool except native-shadowed ones.
"""
# Function-level import: gns3server.agent.mcp pulls the whole MCP
# stack and imports back into gns3_copilot.gns3_client, so importing
# it lazily keeps this module safe during package initialization.
from gns3server.agent.mcp import mcp
if not _adapted_cache:
for mcp_tool in mcp._tool_manager.list_tools():
if mcp_tool.name in MCP_ALLOWED_TOOLS and mcp_tool.name not in NATIVE_TOOL_NAMES:
_adapted_cache[mcp_tool.name] = _adapt(mcp_tool)
if names is None:
return list(_adapted_cache.values())
missing = [name for name in names if name not in _adapted_cache]
if missing:
# Fail loudly at agent construction: a typo or a renamed MCP tool
# must never silently shrink the copilot toolset.
raise RuntimeError(
f"MCP tools not available to the copilot: {missing}. "
f"Allowed pool has {len(_adapted_cache)} tools; check MCP_ALLOWED_TOOLS "
"and the MCP registration."
)
return [_adapted_cache[name] for name in names]
@@ -23,15 +23,23 @@
# Project Home: https://github.com/yueguobin/gns3-copilot
#
"""
Device config entry normalization shared by the tools_v2 executors.
Device config entry normalization shared by the device command runners.
Callers (LLM agents via MCP, or gns3-copilot directly) may send the same
device several times in one batch. Every downstream stage keys by
device_name, so duplicates must merge before execution, not after.
Callers (LLM agents via MCP, or the copilot through the MCP tool bridge)
may send the same device several times in one batch. Every downstream
stage keys by device_name, so duplicates must merge before execution, not
after. This module also renders the optional per-device Jinja2 template
into the commands field.
"""
import logging
from typing import Any
from jinja2 import Template as JinjaTemplate
from jinja2 import TemplateError as JinjaError
logger = logging.getLogger(__name__)
def merge_duplicate_device_configs(
device_configs: list[Any],
@@ -76,3 +84,52 @@ def merge_duplicate_device_configs(
entry[commands_field] = commands
merged[name] = entry
return list(merged.values())
def render_device_template(
template: str,
device_configs: list[dict[str, Any]],
commands_field: str = "config_commands",
) -> list[dict[str, Any]]:
"""
Render a Jinja2 template for each device's vars into the commands field.
Entries with the same device_name are merged into a single entry
so they share one Nornir session and avoid output fragmentation.
Each device in device_configs can have:
- "vars": dict of template variables (rendered into commands_field)
- commands_field: existing commands merged after rendering if present
Returns a one-entry error list on template failure so callers can pass
it straight through to the LLM.
Args:
commands_field: field name for the rendered commands, e.g. "config_commands", "commands"
"""
try:
jinja = JinjaTemplate(template)
except JinjaError as e:
# a syntactically invalid template must not escape as a raw exception
error_msg = f"Template rendering failed: {e}"
logger.error(error_msg)
return [{"status": "failed", "error": error_msg}]
merged: dict[str, dict[str, Any]] = {}
for dev in device_configs:
name = dev.get("device_name")
if not name:
continue
vars_data = dev.get("vars", {})
if name not in merged:
merged[name] = {"device_name": name, commands_field: list(dev.get(commands_field, []))}
entry = merged[name]
if vars_data:
try:
output = jinja.render(**vars_data)
lines = [line for line in output.splitlines() if line.strip()]
entry[commands_field].extend(lines)
except JinjaError as e:
error_msg = f"Template rendering failed for '{name}': {e}"
logger.error(error_msg)
return [{"status": "failed", "error": error_msg}]
return list(merged.values())
+11 -125
View File
@@ -1,6 +1,6 @@
#
# Copyright (C) 2026 GNS3 Technologies Inc.
# Author: Yue Guobin
# Author: YueGuobin
#
# 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
@@ -22,6 +22,10 @@ These tools connect to network device consoles via telnet/SSH and execute
configuration or diagnostic commands. Device connection info is automatically
discovered from the project topology using the device's tags for device_type.
The actual execution lives in the shared runners under
``gns3_copilot/gns3_client/`` (plain classes, no LangChain): the MCP handlers
below and the copilot (through the MCP tool bridge) call the same code.
Prerequisites:
- Device must be started (use node_start / node_start_all)
- Device must have a 'device_type:<type>' tag set in GNS3
@@ -29,141 +33,23 @@ Prerequisites:
- Device must have a console port assigned
"""
import json
import logging
from typing import Any
from jinja2 import Template as JinjaTemplate
from jinja2 import TemplateError as JinjaError
log = logging.getLogger(__name__)
def _render_template(template: str, device_configs: list[dict], commands_field: str = "config_commands") -> list[dict]:
"""Render a Jinja2 template for each device's vars into the specified commands field.
Entries with the same device_name are merged into a single entry
so they share one Nornir session and avoid output fragmentation.
Each device in device_configs can have:
- "vars": dict of template variables (rendered into commands_field)
- commands_field: existing commands merged after rendering if present
Args:
commands_field: field name for the rendered commands, e.g. "config_commands", "commands"
"""
try:
jinja = JinjaTemplate(template)
except JinjaError as e:
# a syntactically invalid template must not escape as a raw exception
error_msg = f"Template rendering failed: {e}"
log.error(error_msg)
return [{"status": "failed", "error": error_msg}]
merged: dict[str, dict] = {}
for dev in device_configs:
name = dev.get("device_name")
if not name:
continue
vars_data = dev.get("vars", {})
if name not in merged:
merged[name] = {"device_name": name, commands_field: list(dev.get(commands_field, []))}
entry = merged[name]
if vars_data:
try:
output = jinja.render(**vars_data)
lines = [l for l in output.splitlines() if l.strip()]
entry[commands_field].extend(lines)
except JinjaError as e:
error_msg = f"Template rendering failed for '{name}': {e}"
log.error(error_msg)
return [{"status": "failed", "error": error_msg}]
return list(merged.values())
# ── Tool handlers ──────────────────────────────────────────────────────────
from gns3server.agent.gns3_copilot.gns3_client.device_config_commands import DeviceConfigCommandRunner
from gns3server.agent.gns3_copilot.gns3_client.device_show_commands import DeviceShowCommandRunner
from gns3server.agent.gns3_copilot.gns3_client.vpcs_commands import VpcsCommandRunner
def device_config_send_handler(params: dict[str, Any], gns3_ctx: dict[str, Any]) -> list[dict[str, Any]]:
"""Send configuration commands to network devices via console."""
project_id = params.get("project_id")
device_configs = params.get("device_configs")
template = params.get("template")
if not project_id or not device_configs:
return [{"status": "failed", "error": "project_id and device_configs are required"}]
if template:
device_configs = _render_template(template, device_configs, commands_field="config_commands")
if len(device_configs) == 1 and "error" in device_configs[0]:
return device_configs
from gns3server.agent.gns3_copilot.tools_v2.config_tools_nornir import ExecuteMultipleDeviceConfigCommands
tool = ExecuteMultipleDeviceConfigCommands()
input_data = json.dumps(
{
"project_id": project_id,
"device_configs": device_configs,
}
)
return tool._run(
input_data,
jwt_token=gns3_ctx["jwt_token"],
url=gns3_ctx["server_url"],
)
return DeviceConfigCommandRunner().run(params, gns3_ctx)
def device_show_run_handler(params: dict[str, Any], gns3_ctx: dict[str, Any]) -> list[dict[str, Any]]:
"""Run read-only diagnostic (show) commands on network devices."""
project_id = params.get("project_id")
device_configs = params.get("device_configs")
template = params.get("template")
if not project_id or not device_configs:
return [
{
"status": "failed",
"error": "project_id and device_configs (list of {device_name, commands}) are required",
}
]
if template:
device_configs = _render_template(template, device_configs, commands_field="commands")
if len(device_configs) == 1 and "error" in device_configs[0]:
return device_configs
from gns3server.agent.gns3_copilot.tools_v2.display_tools_nornir import ExecuteMultipleDeviceCommands
tool = ExecuteMultipleDeviceCommands()
input_data = json.dumps(
{
"project_id": project_id,
"device_configs": device_configs,
}
)
return tool._run(
input_data,
jwt_token=gns3_ctx["jwt_token"],
url=gns3_ctx["server_url"],
)
return DeviceShowCommandRunner().run(params, gns3_ctx)
def vpcs_config_set_handler(params: dict[str, Any], gns3_ctx: dict[str, Any]) -> list[dict[str, Any]]:
"""Configure VPCS devices (set IP, gateway, etc.)."""
project_id = params.get("project_id")
device_configs = params.get("device_configs")
if not project_id or not device_configs:
return [{"status": "failed", "error": "project_id and device_configs are required"}]
from gns3server.agent.gns3_copilot.tools_v2.vpcs_tools_netmiko import VPCSCommands
tool = VPCSCommands()
input_data = json.dumps(
{
"project_id": project_id,
"device_configs": device_configs,
}
)
return tool._run(
input_data,
jwt_token=gns3_ctx["jwt_token"],
url=gns3_ctx["server_url"],
)
return VpcsCommandRunner().run(params, gns3_ctx)