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

@@ -101,22 +101,22 @@ sequenceDiagram
| Tool | teaching_assistant | lab_automation_assistant | troubleshooting_injection |
|---|---|---|---|
| `GNS3TemplateTool` get templates | ✓ | ✓ | |
| `GNS3CreateNodeTool` create nodes | ✓ | ✓ | |
| `GNS3LinkTool` create links | ✓ | ✓ | |
| `GNS3StartNodeTool` start nodes | ✓ | ✓ | |
| `GNS3UpdateNodeNameTool` rename | ✓ | ✓ | |
| `GNS3StopNodeTool` stop nodes | | ✓ | |
| `GNS3SuspendNodeTool` suspend nodes | | ✓ | |
| `ExecuteMultipleDeviceCommands` read-only commands | ✓ | ✓ | ✓ |
| `ExecuteMultipleDeviceConfigCommands` config commands | | ✓ | ✓ |
| `VPCSCommands` VPCS commands | | ✓ | |
| `PacketAnalysisTool` live packet analysis | ✓ | ✓ | |
| `PacketAnalysisSkillsTool` protocol knowledge | ✓ | ✓ | |
| `DeviceSkillsTool` device skills | ✓ | ✓ | |
| `GNS3PacketFilterTool` link filters | | | ✓ |
| `InjectionSkillsTool` fault injection skills | | | ✓ |
| `GNS3TopologyTool` topology info | | | ✓ |
| `template_list` get templates | ✓ | ✓ | |
| `node_create` create nodes | ✓ | ✓ | |
| `link_create` create links (native) | ✓ | ✓ | |
| `node_start` start nodes | ✓ | ✓ | |
| `node_update` rename | ✓ | ✓ | |
| `node_stop` stop nodes | | ✓ | |
| `node_suspend` suspend nodes | | ✓ | |
| `device_show_run` read-only commands | ✓ | ✓ | ✓ |
| `device_config_send` config commands | | ✓ | ✓ |
| `vpcs_config_set` VPCS commands | | ✓ | |
| `packet_analysis` live packet analysis (native) | ✓ | ✓ | |
| `packet_analysis_skills` protocol knowledge (native) | ✓ | ✓ | |
| `device_skill_get` device skills | ✓ | ✓ | |
| `link_update` link filters | | | ✓ |
| `injection_skill_get` fault injection skills | | | ✓ |
| `gns3_topology_reader` topology info (native) | | | ✓ |
The mode is selected in the `llm_call` node via `copilot_mode`, which picks the corresponding tool list and binds it to the LLM model instance through `create_base_model_with_tools(mode_tools, llm_config)`.
+8 -8
View File
@@ -285,7 +285,7 @@ Chat API uses Server-Sent Events (SSE) for streaming transmission.
"tool_call": {
"id": "call_123",
"type": "function",
"function": {"name": "execute_multiple_device_commands", "arguments": ""}
"function": {"name": "device_show_run", "arguments": ""}
},
"session_id": "xxx"
}
@@ -296,7 +296,7 @@ Chat API uses Server-Sent Events (SSE) for streaming transmission.
"tool_call": {
"id": "call_123",
"type": "function",
"function": {"name": "execute_multiple_device_commands", "arguments": "{\"device_names\": [\"R1\"], "}
"function": {"name": "device_show_run", "arguments": "{\"device_names\": [\"R1\"], "}
},
"session_id": "xxx"
}
@@ -307,7 +307,7 @@ Chat API uses Server-Sent Events (SSE) for streaming transmission.
"tool_call": {
"id": "call_123",
"type": "function",
"function": {"name": "execute_multiple_device_commands", "arguments": "{\"device_names\": [\"R1\"], \"commands\": [\"show ver\"]}"}
"function": {"name": "device_show_run", "arguments": "{\"device_names\": [\"R1\"], \"commands\": [\"show ver\"]}"}
},
"session_id": "xxx"
}
@@ -319,7 +319,7 @@ Chat API uses Server-Sent Events (SSE) for streaming transmission.
"id": "call_123",
"type": "function",
"function": {
"name": "execute_multiple_device_commands",
"name": "device_show_run",
"arguments": "{\"device_names\": [\"R1\"], \"commands\": [\"show ver\"]}",
"complete": true
}
@@ -330,7 +330,7 @@ Chat API uses Server-Sent Events (SSE) for streaming transmission.
// Tool starts execution (associated via tool_call_id)
{
"type": "tool_start",
"tool_name": "execute_multiple_device_commands",
"tool_name": "device_show_run",
"tool_call_id": "call_123",
"session_id": "xxx"
}
@@ -338,7 +338,7 @@ Chat API uses Server-Sent Events (SSE) for streaming transmission.
// Tool execution complete
{
"type": "tool_end",
"tool_name": "execute_multiple_device_commands",
"tool_name": "device_show_run",
"tool_output": "[\n {\n \"device_name\": \"R-1\",\n \"status\": \"success\",\n \"output\": \"Cisco IOS Software, \\n IOSv Software (X86_64_LINUX_IOSD-UNIVERSALK9-M), Version 15.2(1.90)\"\n },\n {\n \"device_name\": \"R-2\",\n \"status\": \"failed\",\n \"error\": \"Connection timeout\"\n }\n]",
"session_id": "xxx"
}
@@ -841,8 +841,8 @@ The agent supports two tool sets, selected by `copilot_mode` in the user's LLM c
| Mode | Tools | Description |
|------|-------|-------------|
| `teaching_assistant` (default) | GNS3Template, GNS3CreateNode, GNS3Link, GNS3StartNode, GNS3UpdateNodeName, ExecuteMultipleDeviceCommands, PacketCapture, DeviceSkills | Read-only diagnostic + node creation |
| `lab_automation_assistant` | All teaching_assistant tools + GNS3StopNode, GNS3SuspendNode, ExecuteMultipleDeviceConfigCommands, VPCSCommands | Full diagnostic + configuration tools |
| `teaching_assistant` (default) | GNS3Template, GNS3CreateNode, GNS3Link, GNS3StartNode, GNS3UpdateNodeName, device_show_run, PacketCapture, DeviceSkills | Read-only diagnostic + node creation |
| `lab_automation_assistant` | All teaching_assistant tools + node_stop, node_suspend, device_config_send, vpcs_config_set | Full diagnostic + configuration tools |
**Why Serialize in tool_node?**
@@ -79,8 +79,8 @@ flowchart TD
| Tool | File | Filter | Multi-line Expansion | Result Fields |
|------|------|--------|---------------------|---------------|
| `ExecuteMultipleDeviceCommands` | `display_tools_nornir.py` | Yes | No | `diagnostic_commands` |
| `ExecuteMultipleDeviceConfigCommands` | `config_tools_nornir.py` | Yes | Yes | `config_commands` |
| `device_show_run` | `gns3_client/device_show_commands.py` | Yes | No | `diagnostic_commands` |
| `device_config_send` | `gns3_client/device_config_commands.py` | Yes | Yes | `config_commands` |
## Command Filtering System
@@ -143,8 +143,8 @@ The forbidden commands list is loaded from the external [GNS3-Skills](https://gi
| `reload_forbidden_commands()` | Directly load and cache commands from skills repository |
**Integration points:**
- `display_tools_nornir.py` — `_filter_forbidden_commands_from_device_configs()`
- `config_tools_nornir.py` — `_filter_forbidden_commands_from_device_configs()` + `_expand_multiline_commands()`
- `gns3_client/device_show_commands.py` — `_filter_forbidden_commands_from_device_configs()`
- `gns3_client/device_config_commands.py` — `_filter_forbidden_commands_from_device_configs()` + `_expand_multiline_commands()`
## Configuration Safety (AI Prompt Level)
@@ -158,7 +158,7 @@ In addition to the command filter, the AI agent is instructed via system prompt
## Multi-line Command Handling
Commands containing `\n` are automatically split before execution by `config_tools_nornir.py:_expand_multiline_commands()`.
Commands containing `\n` are automatically split before execution by `device_config_commands.py:_expand_multiline_commands()`.
**Example:** `["banner motd #\nWelcome\n#"]` becomes `["banner motd #", "Welcome", "#"]`
@@ -27,7 +27,7 @@ graph TD
end
subgraph "gns3_copilot.py"
G[llm_call node] --> H[Get topology via GNS3TopologyTool]
G[llm_call node] --> H[Get topology via gns3_topology_reader]
H --> A
A --> I[model_with_tools.invoke]
end
@@ -58,7 +58,7 @@ graph TD
```mermaid
flowchart TD
A[llm_call node invoked] --> B[Get topology via GNS3TopologyTool]
A[llm_call node invoked] --> B[Get topology via gns3_topology_reader]
B --> C[Create pre_model_hook]
C --> D[Inject topology into system prompt]
D --> E{topology data available?}
@@ -133,7 +133,7 @@ In the `llm_call` node of `gns3_copilot.py`:
1. Get `llm_config` from request-scoped context variable
2. Get `project_id` from `config["configurable"]`
3. Retrieve topology via `GNS3TopologyTool._run(project_id)`
3. Retrieve topology via `gns3_topology_reader._run(project_id)`
4. Select tools based on `copilot_mode` (`teaching_assistant` vs `lab_automation_assistant`)
5. Load system prompt and create `pre_model_hook`
6. **Directly call** `pre_hook({"messages": messages, "topology_info": topology_info})` to prepare messages
@@ -16,17 +16,17 @@ flowchart TB
end
subgraph "② Topology Analysis & Fault Selection"
D --> E["GNS3TopologyTool\nget topology info"]
E --> F["ExecuteMultipleDeviceCommands\nget device configs"]
F --> G["InjectionSkillsTool\nquery available fault types"]
D --> E["gns3_topology_reader\nget topology info"]
E --> F["device_show_run\nget device configs"]
F --> G["injection_skill_get\nquery available fault types"]
G --> H{"Injection Skills Repository\ngns3/gns3-skills"}
H --> I["Return matching fault definitions\nwith config injection commands"]
end
subgraph "③ Fault Injection"
I --> J["Choose injection method"]
J --> K["ExecuteMultipleDeviceConfigCommands\ninject config changes"]
J --> L["GNS3PacketFilterTool\ninject link-layer faults"]
J --> K["device_config_send\ninject config changes"]
J --> L["link_update\ninject link-layer faults"]
end
subgraph "④ Result Confirmation"
@@ -40,11 +40,11 @@ flowchart TB
| Tool | Source File | Purpose | Available Modes |
|---|---|---|---|
| `InjectionSkillsTool` | `registry.py` (skills module) | Query protocol-level fault definitions (config change commands) | troubleshooting_injection |
| `GNS3PacketFilterTool` | `gns3_packet_filter.py` | Link-layer fault injection (delay, loss, corruption, BPF) | troubleshooting_injection |
| `ExecuteMultipleDeviceConfigCommands` | `config_tools_nornir.py` | Batch device config changes | troubleshooting_injection |
| `ExecuteMultipleDeviceCommands` | `display_tools_nornir.py` | Read device configurations (read-only) | troubleshooting_injection |
| `GNS3TopologyTool` | `gns3_client` | Get project topology information | troubleshooting_injection |
| `injection_skill_get` | `registry.py` (skills module) | Query protocol-level fault definitions (config change commands) | troubleshooting_injection |
| `link_update` | MCP tool via `tools_v2/mcp_bridge.py` | Link-layer fault injection (delay, loss, corruption, BPF) | troubleshooting_injection |
| `device_config_send` | `gns3_client/device_config_commands.py` | Batch device config changes | troubleshooting_injection |
| `device_show_run` | `gns3_client/device_show_commands.py` | Read device configurations (read-only) | troubleshooting_injection |
| `gns3_topology_reader` | `gns3_client` | Get project topology information | troubleshooting_injection |
## Fault Injection API
@@ -54,7 +54,7 @@ flowchart TB
**Prerequisite**: Project must be in `opened` status, otherwise returns 403.
## GNS3PacketFilterTool Link Filters
## link_update Link Filters
| Filter Type | Function | Parameters |
|---|---|---|
@@ -71,11 +71,11 @@ sequenceDiagram
participant U as User
participant API as POST /chat/inject
participant LLM as LLM Node
participant Topo as GNS3TopologyTool
participant DC as ExecuteMultipleDeviceCommands
participant CC as ExecuteMultipleDeviceConfigCommands
participant Skill as InjectionSkillsTool
participant Filter as GNS3PacketFilterTool
participant Topo as gns3_topology_reader
participant DC as device_show_run
participant CC as device_config_send
participant Skill as injection_skill_get
participant Filter as link_update
U->>API: Inject an OSPF fault
API->>LLM: set mode=troubleshooting_injection
@@ -97,8 +97,8 @@ sequenceDiagram
## Key Design Points
1. **Dedicated API Endpoint** — `POST /chat/inject` is the dedicated entry point, automatically switching to `troubleshooting_injection` mode
2. **LLM-driven Fault Selection** — The LLM analyzes the topology then queries matching faults via `InjectionSkillsTool`; no hardcoded fault scenarios
2. **LLM-driven Fault Selection** — The LLM analyzes the topology then queries matching faults via `injection_skill_get`; no hardcoded fault scenarios
3. **Dual-Layer Injection** — Device-level config changes + link-level network impairment, covering complete troubleshooting scenarios
4. **Fully Reversible** — Every injection includes restore commands; link filters can be cleared with `action: clear`
5. **Safety First** — BPF syntax is pre-validated via tshark; config commands are restricted by `command_filter`
6. **Context Filtering** — `InjectionSkillsTool` requires a `context` parameter, returning only faults matching the topology protocols
6. **Context Filtering** — `injection_skill_get` requires a `context` parameter, returning only faults matching the topology protocols
@@ -26,13 +26,13 @@ graph TD
subgraph "Skills Repository"
IS[INJECTION_SKILLS_REGISTRY<br/>39 categories, 368 issues]
SK[injection_skills Tool]
SK[injection_skill_get Tool]
end
subgraph "Tools"
DC[execute_multiple_device_commands]
CC[execute_multiple_device_config_commands]
GK[GNS3TopologyTool]
DC[device_show_run]
CC[device_config_send]
GK[gns3_topology_reader]
end
TG -->|Get topology| GK
@@ -45,7 +45,7 @@ graph TD
## Injection Skills Tool
The `InjectionSkillsTool` (LangChain `BaseTool`) is the primary interface for querying available faults.
The `injection_skill_get` (LangChain `BaseTool`) is the primary interface for querying available faults.
### Listing Faults (with context filter)
@@ -92,7 +92,7 @@ Token-efficient usage pattern:
```mermaid
sequenceDiagram
participant LLM
participant InjectionSkillsTool
participant injection_skill_get
participant TopologyTool
participant DeviceCommands
@@ -104,14 +104,14 @@ sequenceDiagram
Note over LLM: Analyze which protocols are in use
LLM->>InjectionSkillsTool: {"action": "list", "context": ["ospf", "vlan"]}
InjectionSkillsTool-->>LLM: Matching fault categories
LLM->>injection_skill_get: {"action": "list", "context": ["ospf", "vlan"]}
injection_skill_get-->>LLM: Matching fault categories
LLM->>InjectionSkillsTool: {"device_type": "injection_ospf_issues", "detail": "index"}
InjectionSkillsTool-->>LLM: Issue names (token-efficient)
LLM->>injection_skill_get: {"device_type": "injection_ospf_issues", "detail": "index"}
injection_skill_get-->>LLM: Issue names (token-efficient)
LLM->>InjectionSkillsTool: {"device_type": "injection_ospf_issues", "issue": "ospf_hello_dead_mismatch"}
InjectionSkillsTool-->>LLM: Full fault detail + config commands
LLM->>injection_skill_get: {"device_type": "injection_ospf_issues", "issue": "ospf_hello_dead_mismatch"}
injection_skill_get-->>LLM: Full fault detail + config commands
LLM->>DeviceCommands: Inject fault configuration
DeviceCommands-->>LLM: Execution result
@@ -104,9 +104,9 @@ VPCS output often contains ANSI terminal codes. The `_strip_ansi_codes()` method
### VPCS Tool Usage
The VPCS driver is used by the `execute_vpcs_commands` tool:
The VPCS driver is used by the `vpcs_config_set` tool:
> File: `gns3server/agent/gns3_copilot/tools_v2/vpcs_tools_netmiko.py`
> File: `gns3server/agent/gns3_copilot/gns3_client/vpcs_commands.py`
**VPCS Connection Parameters:**
@@ -172,7 +172,7 @@ The VPCS built-in template includes `"tags": ["device_type:gns3_vpcs_telnet"]`,
**Unified Tool Architecture:**
- ✅ Uses Nornir for connection management (same as network device tools)
- ✅ Uses Netmiko for command execution (consistent with other tools)
- ✅ Follows same patterns as `config_tools_nornir.py` and `display_tools_nornir.py`
- ✅ Follows same patterns as `gns3_client/device_config_commands.py` and `gns3_client/device_show_commands.py`
- ✅ Simplified codebase - no need for separate telnetlib3 implementation
**Migration from telnetlib3:**
@@ -634,7 +634,7 @@ graph TD
### GNS3 Copilot Tool Usage
> Tools: `tools_v2/display_tools_nornir.py`, `tools_v2/config_tools_nornir.py`, `tools_v2/vpcs_tools_netmiko.py`
> Tools: `gns3_client/device_show_commands.py`, `gns3_client/device_config_commands.py`, `gns3_client/vpcs_commands.py`
Each tool reads node tags to determine `device_type`, builds host-level Nornir inventory, and dispatches commands to the appropriate Netmiko driver. Multi-vendor topologies are handled transparently — each device uses its own driver.
@@ -657,17 +657,17 @@ gns3server/agent/gns3_copilot/
│ └── get_gns3_device_port.py # Device port extraction
│ └── get_device_ports_from_topology() # Extract ports + device_type from tags
├── tools_v2/
│ ├── display_tools_nornir.py # Multi-vendor display commands
│ ├── config_tools_nornir.py # Multi-vendor config commands
│ ├── device_show_commands.py # Multi-vendor display commands (shared w/ MCP)
│ ├── device_config_commands.py # Multi-vendor config commands (shared w/ MCP)
│ │ └── _expand_multiline_commands() # Expand banner commands
│ └── vpcs_tools_netmiko.py # VPCS commands using Nornir + Netmiko
│ └── VPCSCommands # VPCS tool class
│ └── vpcs_commands.py # VPCS commands using Nornir + Netmiko (shared w/ MCP)
│ └── vpcs_config_set class # VPCS tool (MCP-shared)
```
**Key Architectural Changes (2026-03-14):**
- ❌ Removed: `vpcs_tools_telnetlib3.py` - Replaced with Netmiko implementation
- ✅ Added: `vpcs_telnet.py` - Custom VPCS driver for Netmiko
- ✅ Added: `vpcs_tools_netmiko.py` - VPCS tool using Nornir + Netmiko
- ✅ Added: `gns3_client/vpcs_commands.py` - VPCS tool using Nornir + Netmiko
- ✅ Simplified: Unified tool architecture - all tools use Nornir + Netmiko
- ✅ Updated: Module structure - all tools follow same pattern
@@ -752,7 +752,7 @@ _Unit Tests: ✅ 52/52 passing (9 Huawei + 15 Ruijie + 28 VPCS)_
_Changelog:_
- **2026-03-14**: Added VPCS support and unified tool architecture
- Implemented `VPCSTelnet` custom Netmiko driver for VPCS simulator
- Replaced `vpcs_tools_telnetlib3.py` with `vpcs_tools_netmiko.py`
- Replaced `vpcs_tools_telnetlib3.py` with `gns3_client/vpcs_commands.py`
- Unified all tools to use Nornir + Netmiko architecture
- Removed dependency on telnetlib3 for VPCS devices
- Improved code consistency and maintainability
@@ -12,11 +12,13 @@ See LICENSE file for licensing information.
GNS3-Copilot provides tools for managing the lifecycle of network devices and topology in GNS3 projects. These tools enable AI agents to create, connect, start, stop, suspend, and manage nodes as part of automated lab management workflows.
> **Tool source (single source of truth):** most copilot tools are no longer hand-written LangChain wrappers. They are adapted from the MCP server's tool registration by `tools_v2/mcp_bridge.py` — tool names, descriptions and argument schemas are identical to the MCP tools (`node_create`, `node_start`, `device_show_run`, ...). The bridge filters the MCP registration down to project-scoped tools (the copilot runs inside one open project; `project_*`, `compute_*`, `appliance_*`, `image_*` and server administration tools are excluded) and bridges the copilot's request JWT into the MCP context. Copilot-native tools remain only where they add value: `link_create` (port-name resolution), `wait_seconds`, `packet_analysis`, `packet_analysis_skills`, `gns3_topology_reader`.
## Available Tools
### GNS3TemplateTool 🆕
### template_list 🆕
**Tool Name:** `get_gns3_templates`
**Tool Name:** `template_list`
**Description:** Retrieves all available device templates from the GNS3 server, including template names, IDs, and types. Filters out built-in utility templates that are not useful for network device configuration.
@@ -70,11 +72,11 @@ The following built-in utility templates are excluded as they are not actual net
**Use Cases:**
- Discover available device types before creating nodes
- Get template_id for GNS3CreateNodeTool
- Get template_id for node_create
- Template inventory management
- Focus on network devices rather than utility templates
### GNS3CreateNodeTool 🆕
### node_create 🆕
**Tool Name:** `node_create`
@@ -138,7 +140,7 @@ The following built-in utility templates are excluded as they are not actual net
**Implementation Details:**
- Calls `POST /projects/{project_id}/nodes` for each node
- Uses template_id from GNS3TemplateTool
- Uses template_id from template_list
- Assigns default names sequentially (e.g., R1, R2, R3)
### GNS3LinkTool 🆕
@@ -200,9 +202,9 @@ The following built-in utility templates are excluded as they are not actual net
- Uses adapter_number and port_number for port identification
- Supports both physical and virtual interfaces
### GNS3UpdateNodeNameTool 🆕
### node_update 🆕
**Tool Name:** `update_gns3_node_name`
**Tool Name:** `node_update`
**Description:** Updates the name of one or multiple nodes in a GNS3 project.
@@ -250,9 +252,9 @@ The following built-in utility templates are excluded as they are not actual net
- Cannot rename while node is started (except special node types)
- CAN rename while node is suspended
### GNS3StartNodeTool
### node_start
**Tool Name:** `start_gns3_node`
**Tool Name:** `node_start`
**Description:** Starts one or multiple nodes in a GNS3 project with progress tracking and status monitoring. Features dynamic wait time calculation based on device types for optimal performance.
@@ -327,7 +329,7 @@ The tool automatically detects node types and calculates optimal wait times:
- Logs device types and selected wait strategy
- Progress bar displays calculated wait time
### GNS3StartNodeQuickTool 🆕
### node_start 🆕
**Tool Name:** `start_gns3_node_quick`
@@ -365,7 +367,7 @@ The tool automatically detects node types and calculates optimal wait times:
**When to Use Quick vs Regular Start:**
| Scenario | Use `start_gns3_node` | Use `start_gns3_node_quick` |
| Scenario | Use `node_start` | Use `start_gns3_node_quick` |
|----------|----------------------|-----------------------------|
| Interactive lab startup | ✅ | ❌ |
| CI/CD pipeline | ❌ | ✅ |
@@ -377,11 +379,11 @@ The tool automatically detects node types and calculates optimal wait times:
- Calls `POST /projects/{project_id}/nodes/{node_id}/start` for each node
- Returns immediately after sending start commands (no progress bar)
- Status reflects command send result, not boot completion
- Source: `gns3_start_node.py` (same file as `GNS3StartNodeTool`)
- Source: MCP tool `node_start`, adapted via `tools_v2/mcp_bridge.py`
### GNS3StopNodeTool
### node_stop
**Tool Name:** `stop_gns3_node`
**Tool Name:** `node_stop`
**Description:** Stops one or multiple nodes in a GNS3 project.
@@ -426,9 +428,9 @@ The tool automatically detects node types and calculates optimal wait times:
- Retrieves updated status after stop command
- Returns detailed results for each node
### GNS3SuspendNodeTool
### node_suspend
**Tool Name:** `suspend_gns3_node`
**Tool Name:** `node_suspend`
**Description:** Suspends one or multiple nodes in a GNS3 project. Suspended nodes preserve their state in memory and can be quickly resumed.
@@ -512,21 +514,18 @@ The tool automatically detects node types and calculates optimal wait times:
```
gns3server/agent/gns3_copilot/tools_v2/
├── gns3_create_node.py # Node creation tool 🆕
├── gns3_create_link.py # Link creation tool 🆕
├── gns3_get_node_temp.py # Template retrieval tool 🆕
├── gns3_update_node_name.py # Node rename tool 🆕
├── gns3_start_node.py # Start node tool (+ GNS3StartNodeQuickTool)
├── gns3_stop_node.py # Stop node tool
├── gns3_suspend_node.py # Suspend node tool
├── config_tools_nornir.py # Configuration command execution
├── display_tools_nornir.py # Display command execution
└── packet_capture_tools.py # Packet capture analysis
├── mcp_bridge.py # Adapts MCP server tools into LangChain tools (most tools)
├── gns3_create_link.py # Native link_create (port-name resolution)
├── gns3_wait.py # Native wait_seconds (boot wait timer)
├── packet_analysis_tool.py # Native packet_analysis (tshark)
├── device_config_commands.py # Shared runner behind MCP device_config_send
├── device_show_commands.py # Shared runner behind MCP device_show_run
└── vpcs_commands.py # Shared runner behind MCP vpcs_config_set
```
### API Integration
The tools call the shared REST handler layer (`gns3_copilot.gns3_client.api_handlers`), the same functions the MCP service exposes as MCP tools:
Most tools are generated from the MCP server registration (`agent/mcp/__init__.py`) by `mcp_bridge.adapted_mcp_tools()` — the MCP registration is the single source of truth for names, descriptions and argument schemas. Underneath, both the MCP tools and the copilot-native tools call the shared REST handler layer (`gns3_copilot.gns3_client.api_handlers`):
```python
from gns3server.agent.gns3_copilot.gns3_client.api_handlers import (
@@ -568,7 +567,7 @@ listing = get_nodes_handler({"project_id": project_id}, gns3_ctx)
### Progress Tracking
**GNS3StartNodeTool** includes visual progress bar with dynamic wait time:
**node_start** includes visual progress bar with dynamic wait time:
```
Starting 3 node(s), please wait...
@@ -577,15 +576,15 @@ Starting 3 node(s), please wait...
Wait time is calculated by `calculate_startup_time()` based on node types (see Dynamic Wait Time Strategy above). No hardcoded duration.
**GNS3StartNodeQuickTool** does NOT include progress tracking:
**node_start** does NOT include progress tracking:
- Returns immediately after sending start commands
- Nodes boot in background
**GNS3StopNodeTool** does not include progress tracking:
**node_stop** does not include progress tracking:
- Stop operations are typically fast (< 5 seconds)
- Immediate API response provides status feedback
**GNS3SuspendNodeTool** does not include progress tracking:
**node_suspend** does not include progress tracking:
- Suspend operations are typically fast (< 10 seconds)
- Immediate API response provides status feedback
@@ -612,19 +611,19 @@ stateDiagram-v2
| **Suspended** | ✅ Yes | ✅ Yes | ❌ No | ✅ Yes |
*Except special node types: cloud, nat, ethernet_switch, ethernet_hub, frame_relay_switch, atm_switch
Note: These special node types are filtered out by GNS3TemplateTool and won't appear in template listings for network lab creation.
Note: These special node types are filtered out by template_list and won't appear in template listings for network lab creation.
## Copilot Mode Integration
### Teaching Assistant Mode
**Tools Available:**
- `GNS3TemplateTool` - List available device templates 🆕
- `GNS3CreateNodeTool` - Create nodes in topology 🆕
- `template_list` - List available device templates 🆕
- `node_create` - Create nodes in topology 🆕
- `GNS3LinkTool` - Create links between nodes 🆕
- `GNS3UpdateNodeNameTool` - Rename nodes 🆕
- `GNS3StartNodeTool` - For diagnostics requiring started nodes
- `ExecuteMultipleDeviceCommands` - Execute show/display/debug commands (READ-ONLY)
- `node_update` - Rename nodes 🆕
- `node_start` - For diagnostics requiring started nodes
- `device_show_run` - Execute show/display/debug commands (READ-ONLY)
- `PacketCaptureTool` - Analyze packets from active capture
- `DeviceSkillsTool` - Get device-specific skills and command knowledge
@@ -637,16 +636,16 @@ Note: These special node types are filtered out by GNS3TemplateTool and won't ap
### Lab Automation Assistant Mode
**Tools Available:**
- `GNS3TemplateTool` - List available device templates 🆕
- `GNS3CreateNodeTool` - Create nodes in topology 🆕
- `template_list` - List available device templates 🆕
- `node_create` - Create nodes in topology 🆕
- `GNS3LinkTool` - Create links between nodes 🆕
- `GNS3UpdateNodeNameTool` - Rename nodes 🆕
- `GNS3StartNodeTool` - Full lab deployment
- `GNS3StopNodeTool` - Full lab shutdown
- `GNS3SuspendNodeTool` - Lab pause with state preservation
- `ExecuteMultipleDeviceCommands` - Execute show/display/debug commands (READ-ONLY)
- `ExecuteMultipleDeviceConfigCommands` - Execute configuration commands
- `VPCSCommands` - Execute VPCS commands using Netmiko
- `node_update` - Rename nodes 🆕
- `node_start` - Full lab deployment
- `node_stop` - Full lab shutdown
- `node_suspend` - Lab pause with state preservation
- `device_show_run` - Execute show/display/debug commands (READ-ONLY)
- `device_config_send` - Execute configuration commands
- `vpcs_config_set` - Execute VPCS commands using Netmiko
- `PacketCaptureTool` - Analyze packets from active capture
- `DeviceSkillsTool` - Get device-specific skills and command knowledge
@@ -662,9 +661,9 @@ Note: These special node types are filtered out by GNS3TemplateTool and won't ap
### Example 1: Start Nodes with Progress
```python
from gns3server.agent.gns3_copilot.tools_v2 import GNS3StartNodeTool
from gns3server.agent.gns3_copilot.tools_v2 import node_start
tool = GNS3StartNodeTool()
tool = node_start()
result = tool._run(json.dumps({"project_id": "abc-123-def", "node_ids": ["node-1", "node-2", "node-3"]}))
# Output includes progress bar and final status
@@ -673,9 +672,9 @@ result = tool._run(json.dumps({"project_id": "abc-123-def", "node_ids": ["node-1
### Example 2: Stop Nodes
```python
from gns3server.agent.gns3_copilot.tools_v2 import GNS3StopNodeTool
from gns3server.agent.gns3_copilot.tools_v2 import node_stop
tool = GNS3StopNodeTool()
tool = node_stop()
result = tool._run(json.dumps({"project_id": "abc-123-def", "node_ids": ["node-1", "node-2"]}))
# Immediate return with stop status
@@ -685,30 +684,30 @@ result = tool._run(json.dumps({"project_id": "abc-123-def", "node_ids": ["node-1
```python
# Lab deployment
start_tool = GNS3StartNodeTool()
start_tool = node_start()
start_result = start_tool._run(json.dumps({"project_id": project_id, "node_ids": all_node_ids}))
# ... Run tests ...
# Lab shutdown
stop_tool = GNS3StopNodeTool()
stop_tool = node_stop()
stop_result = stop_tool._run(json.dumps({"project_id": project_id, "node_ids": all_node_ids}))
```
### Example 4: Lab Pause and Resume
```python
from gns3server.agent.gns3_copilot.tools_v2 import GNS3SuspendNodeTool
from gns3server.agent.gns3_copilot.tools_v2 import node_suspend
# Start lab
start_tool = GNS3StartNodeTool()
start_tool = node_start()
start_result = start_tool._run(json.dumps({"project_id": project_id, "node_ids": all_node_ids}))
# ... Configure devices ...
# ... Run some tests ...
# Suspend lab (preserves all state)
suspend_tool = GNS3SuspendNodeTool()
suspend_tool = node_suspend()
suspend_result = suspend_tool._run(json.dumps({"project_id": project_id, "node_ids": all_node_ids}))
# Nodes suspended - state preserved in memory
@@ -722,14 +721,14 @@ start_result = start_tool._run(json.dumps({"project_id": project_id, "node_ids":
### Example 5: Suspend While Renaming Nodes
```python
from gns3server.agent.gns3_copilot.tools_v2 import GNS3SuspendNodeTool, GNS3UpdateNodeNameTool
from gns3server.agent.gns3_copilot.tools_v2 import node_suspend, node_update
# Suspend nodes first (allows renaming)
suspend_tool = GNS3SuspendNodeTool()
suspend_tool = node_suspend()
suspend_result = suspend_tool._run(json.dumps({"project_id": project_id, "node_ids": node_ids}))
# Now rename nodes (possible while suspended!)
rename_tool = GNS3UpdateNodeNameTool()
rename_tool = node_update()
rename_result = rename_tool._run(
json.dumps(
{
@@ -749,9 +748,9 @@ rename_result = rename_tool._run(
### Example 6: Get Available Templates 🆕
```python
from gns3server.agent.gns3_copilot.tools_v2 import GNS3TemplateTool
from gns3server.agent.gns3_copilot.tools_v2 import template_list
tool = GNS3TemplateTool()
tool = template_list()
result = tool._run("")
# Returns all available device templates
@@ -766,9 +765,9 @@ result = tool._run("")
### Example 7: Create Topology Nodes 🆕
```python
from gns3server.agent.gns3_copilot.tools_v2 import GNS3CreateNodeTool
from gns3server.agent.gns3_copilot.tools_v2 import node_create
tool = GNS3CreateNodeTool()
tool = node_create()
result = tool._run(
json.dumps(
{
@@ -818,9 +817,9 @@ result = tool._run(
### Example 9: Apply Naming Convention 🆕
```python
from gns3server.agent.gns3_copilot.tools_v2 import GNS3UpdateNodeNameTool
from gns3server.agent.gns3_copilot.tools_v2 import node_update
tool = GNS3UpdateNodeNameTool()
tool = node_update()
result = tool._run(
json.dumps(
{
@@ -842,20 +841,20 @@ result = tool._run(
```python
from gns3server.agent.gns3_copilot.tools_v2 import (
GNS3TemplateTool,
GNS3CreateNodeTool,
template_list,
node_create,
GNS3LinkTool,
GNS3UpdateNodeNameTool,
GNS3StartNodeTool,
node_update,
node_start,
)
# Step 1: Get available templates
template_tool = GNS3TemplateTool()
template_tool = template_list()
templates = template_tool._run("")
# Find router and switch template_ids...
# Step 2: Create nodes
create_tool = GNS3CreateNodeTool()
create_tool = node_create()
nodes = create_tool._run(
json.dumps(
{
@@ -894,7 +893,7 @@ links = link_tool._run(
)
# Step 4: Apply naming
name_tool = GNS3UpdateNodeNameTool()
name_tool = node_update()
names = name_tool._run(
json.dumps(
{
@@ -909,7 +908,7 @@ names = name_tool._run(
)
# Step 5: Start nodes
start_tool = GNS3StartNodeTool()
start_tool = node_start()
start_result = start_tool._run(
json.dumps({"project_id": project_id, "node_ids": [n["node_id"] for n in nodes["created_nodes"]]})
)
@@ -1026,7 +1025,7 @@ _Status: ✅ Implemented - Topology management tools available in both modes. Fu
_Changelog:_
- **2026-03-14 (Evening)**: Added dynamic wait time calculation
- `GNS3StartNodeTool` now calculates optimal wait times based on device types
- `node_start` now calculates optimal wait times based on device types
- Fast devices (VPCS: 15s, IOU: 25s) start much faster than before
- Conservative timing accounts for slower hardware environments
- Slow devices (QEMU, Dynamips, etc.) use conservative 120s base time
@@ -1035,6 +1034,6 @@ _Changelog:_
- Logs selected strategy and detected device types
- **2026-03-14 (Morning)**: Added template filtering
- `GNS3TemplateTool` now filters out built-in utility templates (cloud, nat, ethernet_hub, ethernet_switch, frame_relay_switch, atm_switch)
- `template_list` now filters out built-in utility templates (cloud, nat, ethernet_hub, ethernet_switch, frame_relay_switch, atm_switch)
- Focuses on network devices suitable for lab configuration
- Logs filtered count for transparency
@@ -10,7 +10,7 @@ See LICENSE file for licensing information.
```mermaid
flowchart TB
subgraph "① Analysis Trigger & Knowledge Query"
A["User asks\n'e.g. Analyze OSPF neighbor state'"] --> B["LLM calls\nPacketAnalysisSkillsTool"]
A["User asks\n'e.g. Analyze OSPF neighbor state'"] --> B["LLM calls\npacket_analysis_skills"]
B --> C{"Protocol Knowledge Repository\ngns3/gns3-skills"}
C --> D["Returns protocol definition\nfields/base_filter/check_rules"]
B --> E["LLM calls\nsearch_fields mode"]
@@ -21,7 +21,7 @@ flowchart TB
subgraph "② Live Capture & Analysis"
D --> H["LLM constructs tshark_args"]
G --> H
H --> I["PacketAnalysisTool\ncapture analysis mode"]
H --> I["packet_analysis\ncapture analysis mode"]
I --> J["GET /capture/file\ndownload live PCAP"]
J --> K["Pre-validate -e field names"]
K --> L["tshark -r pcap\nrun analysis"]
@@ -33,8 +33,8 @@ flowchart TB
| Tool | Source File | Purpose | Available Modes |
|---|---|---|---|
| `PacketAnalysisTool` | `packet_analysis_tool.py` | Download live PCAP + tshark analysis | teaching / lab_automation |
| `PacketAnalysisSkillsTool` | `registry.py` (skills module) | Query protocol-level analysis knowledge (fields, filters) | teaching / lab_automation |
| `packet_analysis` | `packet_analysis_tool.py` | Download live PCAP + tshark analysis | teaching / lab_automation |
| `packet_analysis_skills` | `registry.py` (skills module) | Query protocol-level analysis knowledge (fields, filters) | teaching / lab_automation |
## Agent Workflow (LangGraph)
@@ -42,8 +42,8 @@ flowchart TB
sequenceDiagram
participant U as User
participant LLM as LLM Node
participant Skills as PacketAnalysisSkillsTool
participant Pcap as PacketAnalysisTool
participant Skills as packet_analysis_skills
participant Pcap as packet_analysis
U->>LLM: OSPF neighbors can't establish, analyze
LLM->>Skills: get protocol=ospf
@@ -12,7 +12,7 @@ See LICENSE file for licensing information.
GNS3 Copilot provides protocol-oriented packet analysis that allows the AI assistant to diagnose network issues from live GNS3 captures. Protocol definitions (tshark fields, display filters, check rules) are stored as YAML files in the external GNS3-Skills repository and loaded into memory at startup.
The system exposes two LangChain tools: `PacketAnalysisSkillsTool` queries protocol definitions, and `PacketAnalysisTool` runs tshark against downloaded pcap files using the LLM-constructed arguments.
The system exposes two LangChain tools: `packet_analysis_skills` queries protocol definitions, and `packet_analysis` runs tshark against downloaded pcap files using the LLM-constructed arguments.
## Architecture
@@ -26,8 +26,8 @@ graph TD
SM[SkillsManager]
SL[SkillsLoader]
REG[PACKET_ANALYSIS_REGISTRY<br/>in-memory dict]
SKILL[PacketAnalysisSkillsTool<br/>query protocol definitions]
TOOL[PacketAnalysisTool<br/>run tshark on captures]
SKILL[packet_analysis_skills<br/>query protocol definitions]
TOOL[packet_analysis<br/>run tshark on captures]
end
subgraph "tshark"
@@ -89,8 +89,8 @@ checks:
```mermaid
sequenceDiagram
participant LLM as LLM Agent
participant SKILL as PacketAnalysisSkillsTool
participant TOOL as PacketAnalysisTool
participant SKILL as packet_analysis_skills
participant TOOL as packet_analysis
participant tshark as tshark
participant GNS3 as GNS3 Server
@@ -117,12 +117,12 @@ The packet analysis tools are available in two copilot modes:
| Tool | Teaching Assistant | Lab Automation | Troubleshooting Injection |
|------|:------------------:|:--------------:|:-------------------------:|
| `PacketAnalysisTool` | Yes | Yes | No |
| `PacketAnalysisSkillsTool` | Yes | Yes | No |
| `packet_analysis` | Yes | Yes | No |
| `packet_analysis_skills` | Yes | Yes | No |
## Tool Interface
### PacketAnalysisSkillsTool (`packet_analysis_skills`)
### packet_analysis_skills
Queries protocol definitions from the `PACKET_ANALYSIS_REGISTRY`. Used before running tshark to look up valid field names, display filters, and anomaly checks.
@@ -131,7 +131,7 @@ Queries protocol definitions from the `PACKET_ANALYSIS_REGISTRY`. Used before ru
| List protocols | `{"action": "list"}` | `{count, protocols: [{protocol, name, description}]}` |
| Get protocol | `{"action": "get", "protocol": "ospf"}` | Protocol definition with fields, filters, checks |
### PacketAnalysisTool (`packet_analysis`)
### packet_analysis
Runs tshark against a downloaded GNS3 capture file. Supports two modes:
@@ -82,7 +82,7 @@ SKILLS_REGISTRY["frr_vtysh"] = { ..._base.yaml..., "topics": { "ospf": {...}, "b
Topic files must declare `device_type` (matching their `_base.yaml`), `topic` and `name`; the CI validator in the skills repository enforces this.
The `device_skills` tool exposes a three-step drill-down (mirroring `injection_skills`'s list → index → issue pattern):
The `device_skill_get` tool exposes a three-step drill-down (mirroring `injection_skill_get`'s list → index → issue pattern):
```json
{"action": "list"}
@@ -101,8 +101,8 @@ Systematically inject network faults and validate AIOps detection using the exis
### 2.2 Fault Injection
- Use existing `manage_gns3_packet_filter` tool for network-level faults
- Use existing `execute_multiple_device_config_commands` for configuration faults
- Use existing `link_update` tool for network-level faults
- Use existing `device_config_send` for configuration faults
- Use existing `InjectionSkillsTool` to query and select appropriate faults
- Support combined faults (multiple simultaneous issues)
- Auto-recovery between scenarios (restore baseline state)
@@ -61,4 +61,4 @@ The `troubleshooting_injection.md` prompt in the GNS3-Skills repository gains an
- [ ] gns3-server: implement injection fault recording in agent chat session flow
- [ ] gns3-server: implement injection history query across sessions per project
- [ ] gns3-server: inject history into system prompt via `context_manager.py`
- [ ] gns3-server: add `exclude` parameter to `InjectionSkillsTool` for filtering used faults
- [ ] gns3-server: add `exclude` parameter to `injection_skill_get` for filtering used faults
@@ -161,7 +161,7 @@ User Request: "Configure OSPF on all routers"
│ │
│ Process: │
│ 1. Render template with parameters (0 tokens) │
│ 2. Call existing ExecuteMultipleDeviceConfigCommands │
│ 2. Call existing device_config_send │
│ 3. Return execution results │
└─────────────────────────────────────────────────────────────┘
```
@@ -2068,7 +2068,7 @@ langgraph>=0.0.20
### Integration Points
- `gns3server/agent/gns3_copilot/tools_v2/config_tools_nornir.py` (existing)
- `gns3server/agent/gns3_copilot/gns3_client/device_config_commands.py` (existing)
- `gns3server/agent/gns3_copilot/prompts/lab_automation_assistant_prompt.py` (update)
- `gns3server/agent/gns3_copilot/gns3_client/gns3_topology_reader.py` (existing)
- `gns3server/agent/gns3_copilot/utils/command_filter.py` (existing)