diff --git a/docs/gns3-copilot/implemented/ai-assistant-overview.en.md b/docs/gns3-copilot/implemented/ai-assistant-overview.en.md index b01c1d20f..9813c59a3 100644 --- a/docs/gns3-copilot/implemented/ai-assistant-overview.en.md +++ b/docs/gns3-copilot/implemented/ai-assistant-overview.en.md @@ -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)`. diff --git a/docs/gns3-copilot/implemented/chat-api.md b/docs/gns3-copilot/implemented/chat-api.md index 22cc9341b..104357677 100644 --- a/docs/gns3-copilot/implemented/chat-api.md +++ b/docs/gns3-copilot/implemented/chat-api.md @@ -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?** diff --git a/docs/gns3-copilot/implemented/command-security.md b/docs/gns3-copilot/implemented/command-security.md index 1e84b2f7a..a741fd483 100644 --- a/docs/gns3-copilot/implemented/command-security.md +++ b/docs/gns3-copilot/implemented/command-security.md @@ -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", "#"]` diff --git a/docs/gns3-copilot/implemented/context-window-management.md b/docs/gns3-copilot/implemented/context-window-management.md index 4e179e455..4591afd5e 100644 --- a/docs/gns3-copilot/implemented/context-window-management.md +++ b/docs/gns3-copilot/implemented/context-window-management.md @@ -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 diff --git a/docs/gns3-copilot/implemented/fault-injection-overview.en.md b/docs/gns3-copilot/implemented/fault-injection-overview.en.md index 6d947e942..e41da85a2 100644 --- a/docs/gns3-copilot/implemented/fault-injection-overview.en.md +++ b/docs/gns3-copilot/implemented/fault-injection-overview.en.md @@ -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 diff --git a/docs/gns3-copilot/implemented/fault-injection.md b/docs/gns3-copilot/implemented/fault-injection.md index b33bd52da..92a9d8380 100644 --- a/docs/gns3-copilot/implemented/fault-injection.md +++ b/docs/gns3-copilot/implemented/fault-injection.md @@ -26,13 +26,13 @@ graph TD subgraph "Skills Repository" IS[INJECTION_SKILLS_REGISTRY
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 diff --git a/docs/gns3-copilot/implemented/multi-vendor-device-support.md b/docs/gns3-copilot/implemented/multi-vendor-device-support.md index 8dde4759b..6f95970f3 100644 --- a/docs/gns3-copilot/implemented/multi-vendor-device-support.md +++ b/docs/gns3-copilot/implemented/multi-vendor-device-support.md @@ -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 diff --git a/docs/gns3-copilot/implemented/node-control-tools.md b/docs/gns3-copilot/implemented/node-control-tools.md index f1f411601..9a39198b9 100644 --- a/docs/gns3-copilot/implemented/node-control-tools.md +++ b/docs/gns3-copilot/implemented/node-control-tools.md @@ -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 diff --git a/docs/gns3-copilot/implemented/packet-analysis-overview.en.md b/docs/gns3-copilot/implemented/packet-analysis-overview.en.md index ba11a7aa3..6760c4f73 100644 --- a/docs/gns3-copilot/implemented/packet-analysis-overview.en.md +++ b/docs/gns3-copilot/implemented/packet-analysis-overview.en.md @@ -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 diff --git a/docs/gns3-copilot/implemented/packet-analysis.md b/docs/gns3-copilot/implemented/packet-analysis.md index d77ed3404..9164c25e3 100644 --- a/docs/gns3-copilot/implemented/packet-analysis.md +++ b/docs/gns3-copilot/implemented/packet-analysis.md @@ -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
in-memory dict] - SKILL[PacketAnalysisSkillsTool
query protocol definitions] - TOOL[PacketAnalysisTool
run tshark on captures] + SKILL[packet_analysis_skills
query protocol definitions] + TOOL[packet_analysis
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: diff --git a/docs/gns3-copilot/implemented/skills-repository.md b/docs/gns3-copilot/implemented/skills-repository.md index 76f9e3c96..9a5441630 100644 --- a/docs/gns3-copilot/implemented/skills-repository.md +++ b/docs/gns3-copilot/implemented/skills-repository.md @@ -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"} diff --git a/docs/gns3-copilot/roadmap/aiops-fault-injection-testing-pipeline-roadmap.md b/docs/gns3-copilot/roadmap/aiops-fault-injection-testing-pipeline-roadmap.md index 760785efd..1c7047a58 100644 --- a/docs/gns3-copilot/roadmap/aiops-fault-injection-testing-pipeline-roadmap.md +++ b/docs/gns3-copilot/roadmap/aiops-fault-injection-testing-pipeline-roadmap.md @@ -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) diff --git a/docs/gns3-copilot/roadmap/injection-fault-tracking-roadmap.md b/docs/gns3-copilot/roadmap/injection-fault-tracking-roadmap.md index 6ad782d7c..104ac3952 100644 --- a/docs/gns3-copilot/roadmap/injection-fault-tracking-roadmap.md +++ b/docs/gns3-copilot/roadmap/injection-fault-tracking-roadmap.md @@ -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 diff --git a/docs/gns3-copilot/roadmap/template-based-configuration-roadmap.md b/docs/gns3-copilot/roadmap/template-based-configuration-roadmap.md index 637da5d79..017e1b384 100644 --- a/docs/gns3-copilot/roadmap/template-based-configuration-roadmap.md +++ b/docs/gns3-copilot/roadmap/template-based-configuration-roadmap.md @@ -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) diff --git a/gns3server/agent/gns3_copilot/agent/gns3_copilot.py b/gns3server/agent/gns3_copilot/agent/gns3_copilot.py index 822c54b20..9868040d8 100644 --- a/gns3server/agent/gns3_copilot/agent/gns3_copilot.py +++ b/gns3server/agent/gns3_copilot/agent/gns3_copilot.py @@ -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) diff --git a/gns3server/agent/gns3_copilot/tools_v2/config_tools_nornir.py b/gns3server/agent/gns3_copilot/gns3_client/device_config_commands.py similarity index 89% rename from gns3server/agent/gns3_copilot/tools_v2/config_tools_nornir.py rename to gns3server/agent/gns3_copilot/gns3_client/device_config_commands.py index 5d2506a65..99606043f 100644 --- a/gns3server/agent/gns3_copilot/tools_v2/config_tools_nornir.py +++ b/gns3server/agent/gns3_copilot/gns3_client/device_config_commands.py @@ -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": "", - "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": diff --git a/gns3server/agent/gns3_copilot/tools_v2/display_tools_nornir.py b/gns3server/agent/gns3_copilot/gns3_client/device_show_commands.py similarity index 90% rename from gns3server/agent/gns3_copilot/tools_v2/display_tools_nornir.py rename to gns3server/agent/gns3_copilot/gns3_client/device_show_commands.py index bbb92b0c5..02266483a 100644 --- a/gns3server/agent/gns3_copilot/tools_v2/display_tools_nornir.py +++ b/gns3server/agent/gns3_copilot/gns3_client/device_show_commands.py @@ -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": "", - "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": diff --git a/gns3server/agent/gns3_copilot/tools_v2/vpcs_tools_netmiko.py b/gns3server/agent/gns3_copilot/gns3_client/vpcs_commands.py similarity index 89% rename from gns3server/agent/gns3_copilot/tools_v2/vpcs_tools_netmiko.py rename to gns3server/agent/gns3_copilot/gns3_client/vpcs_commands.py index 081566b22..acc114f17 100644 --- a/gns3server/agent/gns3_copilot/tools_v2/vpcs_tools_netmiko.py +++ b/gns3server/agent/gns3_copilot/gns3_client/vpcs_commands.py @@ -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
/ @@ -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": "", - "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)) diff --git a/gns3server/agent/gns3_copilot/tools_v2/__init__.py b/gns3server/agent/gns3_copilot/tools_v2/__init__.py index 078105ada..de1970248 100644 --- a/gns3server/agent/gns3_copilot/tools_v2/__init__.py +++ b/gns3server/agent/gns3_copilot/tools_v2/__init__.py @@ -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__})") diff --git a/gns3server/agent/gns3_copilot/tools_v2/gns3_create_drawing.py b/gns3server/agent/gns3_copilot/tools_v2/gns3_create_drawing.py deleted file mode 100644 index f541bdc14..000000000 --- a/gns3server/agent/gns3_copilot/tools_v2/gns3_create_drawing.py +++ /dev/null @@ -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 . -# -# 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) diff --git a/gns3server/agent/gns3_copilot/tools_v2/gns3_create_node.py b/gns3server/agent/gns3_copilot/tools_v2/gns3_create_node.py deleted file mode 100644 index bd6081201..000000000 --- a/gns3server/agent/gns3_copilot/tools_v2/gns3_create_node.py +++ /dev/null @@ -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 . -# -# 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) diff --git a/gns3server/agent/gns3_copilot/tools_v2/gns3_get_node_temp.py b/gns3server/agent/gns3_copilot/tools_v2/gns3_get_node_temp.py deleted file mode 100644 index 594c2c2cf..000000000 --- a/gns3server/agent/gns3_copilot/tools_v2/gns3_get_node_temp.py +++ /dev/null @@ -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 . -# -# 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) diff --git a/gns3server/agent/gns3_copilot/tools_v2/gns3_packet_filter.py b/gns3server/agent/gns3_copilot/tools_v2/gns3_packet_filter.py deleted file mode 100644 index 0bb83eba1..000000000 --- a/gns3server/agent/gns3_copilot/tools_v2/gns3_packet_filter.py +++ /dev/null @@ -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 . -# -# 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) diff --git a/gns3server/agent/gns3_copilot/tools_v2/gns3_start_node.py b/gns3server/agent/gns3_copilot/tools_v2/gns3_start_node.py deleted file mode 100644 index 2fb17f8f8..000000000 --- a/gns3server/agent/gns3_copilot/tools_v2/gns3_start_node.py +++ /dev/null @@ -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 . -# -# 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": "", # 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) diff --git a/gns3server/agent/gns3_copilot/tools_v2/gns3_stop_node.py b/gns3server/agent/gns3_copilot/tools_v2/gns3_stop_node.py deleted file mode 100644 index b4ef8cfd5..000000000 --- a/gns3server/agent/gns3_copilot/tools_v2/gns3_stop_node.py +++ /dev/null @@ -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 . -# -# 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": "", # 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": "", # 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) diff --git a/gns3server/agent/gns3_copilot/tools_v2/gns3_suspend_node.py b/gns3server/agent/gns3_copilot/tools_v2/gns3_suspend_node.py deleted file mode 100644 index 25dda50fd..000000000 --- a/gns3server/agent/gns3_copilot/tools_v2/gns3_suspend_node.py +++ /dev/null @@ -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 . -# -# 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": "", # 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": "", # 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) diff --git a/gns3server/agent/gns3_copilot/tools_v2/gns3_update_node_name.py b/gns3server/agent/gns3_copilot/tools_v2/gns3_update_node_name.py deleted file mode 100644 index 3121bc598..000000000 --- a/gns3server/agent/gns3_copilot/tools_v2/gns3_update_node_name.py +++ /dev/null @@ -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 . -# -# 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) diff --git a/gns3server/agent/gns3_copilot/tools_v2/gns3_wait.py b/gns3server/agent/gns3_copilot/tools_v2/gns3_wait.py index ed2f12802..979754953 100644 --- a/gns3server/agent/gns3_copilot/tools_v2/gns3_wait.py +++ b/gns3server/agent/gns3_copilot/tools_v2/gns3_wait.py @@ -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. diff --git a/gns3server/agent/gns3_copilot/tools_v2/mcp_bridge.py b/gns3server/agent/gns3_copilot/tools_v2/mcp_bridge.py new file mode 100644 index 000000000..a48150d0c --- /dev/null +++ b/gns3server/agent/gns3_copilot/tools_v2/mcp_bridge.py @@ -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 . +# +# 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] diff --git a/gns3server/agent/gns3_copilot/utils/device_configs.py b/gns3server/agent/gns3_copilot/utils/device_configs.py index f5ff4575f..bd2d0aed9 100644 --- a/gns3server/agent/gns3_copilot/utils/device_configs.py +++ b/gns3server/agent/gns3_copilot/utils/device_configs.py @@ -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()) diff --git a/gns3server/agent/mcp/device_config.py b/gns3server/agent/mcp/device_config.py index be7f04356..5f3ba85a0 100644 --- a/gns3server/agent/mcp/device_config.py +++ b/gns3server/agent/mcp/device_config.py @@ -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:' 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) diff --git a/tests/agent/mcp/test_device_tools.py b/tests/agent/mcp/test_device_tools.py index c03bddd88..716fa8b7f 100644 --- a/tests/agent/mcp/test_device_tools.py +++ b/tests/agent/mcp/test_device_tools.py @@ -16,9 +16,9 @@ from gns3server.agent.gns3_copilot.utils.device_configs import ( merge_duplicate_device_configs, ) -VPCS_MOD = "gns3server.agent.gns3_copilot.tools_v2.vpcs_tools_netmiko" -DISPLAY_MOD = "gns3server.agent.gns3_copilot.tools_v2.display_tools_nornir" -CONFIG_MOD = "gns3server.agent.gns3_copilot.tools_v2.config_tools_nornir" +VPCS_MOD = "gns3server.agent.gns3_copilot.gns3_client.vpcs_commands" +DISPLAY_MOD = "gns3server.agent.gns3_copilot.gns3_client.device_show_commands" +CONFIG_MOD = "gns3server.agent.gns3_copilot.gns3_client.device_config_commands" PROJECT_ID = "0c0fde25-6ead-4413-a283-ea8fd2324291" @@ -50,10 +50,10 @@ def _aggregated_result(output_by_device): class TestVPCSNodeTypeGuard: def test_non_vpcs_node_is_rejected(self): - from gns3server.agent.gns3_copilot.tools_v2.vpcs_tools_netmiko import VPCSCommands + from gns3server.agent.gns3_copilot.gns3_client.vpcs_commands import VpcsCommandRunner with patch(f"{VPCS_MOD}.get_device_ports_from_topology", return_value=_topology_ports("iou")) as topo: - result = VPCSCommands()._run( + result = VpcsCommandRunner().run( json.dumps( { "project_id": "0c0fde25-6ead-4413-a283-ea8fd2324291", @@ -68,10 +68,10 @@ class TestVPCSNodeTypeGuard: assert "not a VPCS node" in result[0]["error"] def test_missing_node_type_is_rejected(self): - from gns3server.agent.gns3_copilot.tools_v2.vpcs_tools_netmiko import VPCSCommands + from gns3server.agent.gns3_copilot.gns3_client.vpcs_commands import VpcsCommandRunner with patch(f"{VPCS_MOD}.get_device_ports_from_topology", return_value={"PC1": {"port": 5000}}): - result = VPCSCommands()._run( + result = VpcsCommandRunner().run( json.dumps( { "project_id": "0c0fde25-6ead-4413-a283-ea8fd2324291", @@ -83,18 +83,18 @@ class TestVPCSNodeTypeGuard: assert "unknown-type" in result[0]["error"] def test_vpcs_node_passes_the_guard(self): - from gns3server.agent.gns3_copilot.tools_v2.vpcs_tools_netmiko import VPCSCommands + from gns3server.agent.gns3_copilot.gns3_client.vpcs_commands import VpcsCommandRunner - tool = VPCSCommands() + tool = VpcsCommandRunner() nornir = MagicMock() host_result = MagicMock(failed=False) host_result.result = "OK" nornir.run.return_value = {"PC1": host_result} with ( patch(f"{VPCS_MOD}.get_device_ports_from_topology", return_value=_topology_ports("vpcs")), - patch.object(VPCSCommands, "_initialize_nornir", return_value=nornir), + patch.object(VpcsCommandRunner, "_initialize_nornir", return_value=nornir), ): - result = tool._run( + result = tool.run( json.dumps( { "project_id": "0c0fde25-6ead-4413-a283-ea8fd2324291", @@ -106,18 +106,18 @@ class TestVPCSNodeTypeGuard: assert result[0]["output"] == "OK" def test_execution_failure_reports_failed_with_error(self): - from gns3server.agent.gns3_copilot.tools_v2.vpcs_tools_netmiko import VPCSCommands + from gns3server.agent.gns3_copilot.gns3_client.vpcs_commands import VpcsCommandRunner - tool = VPCSCommands() + tool = VpcsCommandRunner() nornir = MagicMock() host_result = MagicMock(failed=True) host_result.result = "Command failed (ReadTimeout)" nornir.run.return_value = {"PC1": host_result} with ( patch(f"{VPCS_MOD}.get_device_ports_from_topology", return_value=_topology_ports("vpcs")), - patch.object(VPCSCommands, "_initialize_nornir", return_value=nornir), + patch.object(VpcsCommandRunner, "_initialize_nornir", return_value=nornir), ): - result = tool._run( + result = tool.run( json.dumps( { "project_id": "0c0fde25-6ead-4413-a283-ea8fd2324291", @@ -138,7 +138,7 @@ class TestVPCSConsoleHostPropagation: """ def test_remote_compute_hostname_reaches_nornir_inventory(self): - from gns3server.agent.gns3_copilot.tools_v2.vpcs_tools_netmiko import VPCSCommands + from gns3server.agent.gns3_copilot.gns3_client.vpcs_commands import VpcsCommandRunner with patch( f"{VPCS_MOD}.get_device_ports_from_topology", @@ -147,7 +147,7 @@ class TestVPCSConsoleHostPropagation: "PC2": {"port": 5001, "node_type": "vpcs"}, }, ): - hosts_data = VPCSCommands()._prepare_device_hosts_data( + hosts_data = VpcsCommandRunner()._prepare_device_hosts_data( [ {"device_name": "PC1", "commands": ["ip 10.0.0.1/24"]}, {"device_name": "PC2", "commands": ["ip 10.0.0.2/24"]}, @@ -167,10 +167,10 @@ class TestDeviceToolErrorContract: """ def test_topology_level_error_has_status(self): - from gns3server.agent.gns3_copilot.tools_v2.vpcs_tools_netmiko import VPCSCommands + from gns3server.agent.gns3_copilot.gns3_client.vpcs_commands import VpcsCommandRunner with patch(f"{VPCS_MOD}.get_device_ports_from_topology", side_effect=ValueError("topology unreachable")): - result = VPCSCommands()._run( + result = VpcsCommandRunner().run( json.dumps( { "project_id": "0c0fde25-6ead-4413-a283-ea8fd2324291", @@ -181,15 +181,15 @@ class TestDeviceToolErrorContract: assert result == [{"status": "failed", "error": "topology unreachable"}] def test_config_tool_topology_level_error_has_status(self): - from gns3server.agent.gns3_copilot.tools_v2.config_tools_nornir import ( - ExecuteMultipleDeviceConfigCommands, + from gns3server.agent.gns3_copilot.gns3_client.device_config_commands import ( + DeviceConfigCommandRunner, ) with patch( - "gns3server.agent.gns3_copilot.tools_v2.config_tools_nornir.get_device_ports_from_topology", + "gns3server.agent.gns3_copilot.gns3_client.device_config_commands.get_device_ports_from_topology", side_effect=ValueError("no valid devices"), ): - result = ExecuteMultipleDeviceConfigCommands()._run( + result = DeviceConfigCommandRunner().run( json.dumps( { "project_id": "0c0fde25-6ead-4413-a283-ea8fd2324291", @@ -217,13 +217,45 @@ class TestDeviceToolErrorContract: assert "required" in result[0]["error"] def test_template_render_error_has_status(self): - from gns3server.agent.mcp.device_config import _render_template + from gns3server.agent.gns3_copilot.utils.device_configs import render_device_template - result = _render_template("{{ unclosed", [{"device_name": "R1", "vars": {"n": 1}}]) + result = render_device_template("{{ unclosed", [{"device_name": "R1", "vars": {"n": 1}}]) assert len(result) == 1 assert result[0]["status"] == "failed" assert "Template rendering failed" in result[0]["error"] + def test_template_flows_through_the_config_runner(self): + """The optional Jinja2 template reaches the execution layer rendered.""" + from gns3server.agent.gns3_copilot.gns3_client.device_config_commands import ( + DeviceConfigCommandRunner, + ) + + nornir = MagicMock() + nornir.run.return_value = _aggregated_result({"R1": "ok", "R2": "ok"}) + with ( + patch( + f"{CONFIG_MOD}.get_device_ports_from_topology", + return_value={"R1": {"port": 5000, "node_type": "iou"}, "R2": {"port": 5001, "node_type": "iou"}}, + ), + patch.object(DeviceConfigCommandRunner, "_initialize_nornir", return_value=nornir), + ): + result = DeviceConfigCommandRunner().run( + { + "project_id": PROJECT_ID, + "template": "interface lo{{ n }}\nip address {{ ip }} 255.255.255.255", + "device_configs": [ + {"device_name": "R1", "vars": {"n": 0, "ip": "1.1.1.1"}}, + {"device_name": "R2", "vars": {"n": 1, "ip": "2.2.2.2"}}, + ], + } + ) + + assert nornir.run.call_args.kwargs["device_configs_map"] == { + "R1": ["interface lo0", "ip address 1.1.1.1 255.255.255.255"], + "R2": ["interface lo1", "ip address 2.2.2.2 255.255.255.255"], + } + assert [row["device_name"] for row in result] == ["R1", "R2"] + class TestDuplicateDeviceMerging: """ @@ -236,17 +268,17 @@ class TestDuplicateDeviceMerging: """ def test_show_run_merges_same_device_entries(self): - from gns3server.agent.gns3_copilot.tools_v2.display_tools_nornir import ( - ExecuteMultipleDeviceCommands, + from gns3server.agent.gns3_copilot.gns3_client.device_show_commands import ( + DeviceShowCommandRunner, ) nornir = MagicMock() nornir.run.return_value = _aggregated_result({"R1": "merged output", "R2": "r2 output"}) with ( patch(f"{DISPLAY_MOD}.get_device_ports_from_topology", return_value=_topology_two_devices()), - patch.object(ExecuteMultipleDeviceCommands, "_initialize_nornir", return_value=nornir), + patch.object(DeviceShowCommandRunner, "_initialize_nornir", return_value=nornir), ): - result = ExecuteMultipleDeviceCommands()._run( + result = DeviceShowCommandRunner().run( json.dumps( { "project_id": PROJECT_ID, @@ -271,8 +303,8 @@ class TestDuplicateDeviceMerging: assert result[0]["diagnostic_commands"] == ["show ip route", "show ip interface brief"] def test_config_send_merges_same_device_entries(self): - from gns3server.agent.gns3_copilot.tools_v2.config_tools_nornir import ( - ExecuteMultipleDeviceConfigCommands, + from gns3server.agent.gns3_copilot.gns3_client.device_config_commands import ( + DeviceConfigCommandRunner, ) nornir = MagicMock() @@ -281,9 +313,9 @@ class TestDuplicateDeviceMerging: patch( f"{CONFIG_MOD}.get_device_ports_from_topology", return_value={"R1": {"port": 5000, "node_type": "iou"}} ), - patch.object(ExecuteMultipleDeviceConfigCommands, "_initialize_nornir", return_value=nornir), + patch.object(DeviceConfigCommandRunner, "_initialize_nornir", return_value=nornir), ): - result = ExecuteMultipleDeviceConfigCommands()._run( + result = DeviceConfigCommandRunner().run( json.dumps( { "project_id": PROJECT_ID, @@ -303,7 +335,7 @@ class TestDuplicateDeviceMerging: assert result[0]["config_commands"] == ["int lo0", "ip address 1.1.1.1 255.255.255.255", "exit"] def test_vpcs_merges_same_device_entries(self): - from gns3server.agent.gns3_copilot.tools_v2.vpcs_tools_netmiko import VPCSCommands + from gns3server.agent.gns3_copilot.gns3_client.vpcs_commands import VpcsCommandRunner nornir = MagicMock() host_result = MagicMock(failed=False) @@ -311,9 +343,9 @@ class TestDuplicateDeviceMerging: nornir.run.return_value = {"PC1": host_result} with ( patch(f"{VPCS_MOD}.get_device_ports_from_topology", return_value=_topology_ports("vpcs")), - patch.object(VPCSCommands, "_initialize_nornir", return_value=nornir), + patch.object(VpcsCommandRunner, "_initialize_nornir", return_value=nornir), ): - result = VPCSCommands()._run( + result = VpcsCommandRunner().run( json.dumps( { "project_id": PROJECT_ID, @@ -332,8 +364,8 @@ class TestDuplicateDeviceMerging: def test_blocked_commands_accumulate_across_duplicate_entries(self): """Blocked-command info must not last-win between same-device entries.""" - from gns3server.agent.gns3_copilot.tools_v2.display_tools_nornir import ( - ExecuteMultipleDeviceCommands, + from gns3server.agent.gns3_copilot.gns3_client.device_show_commands import ( + DeviceShowCommandRunner, ) def fake_filter(commands): @@ -347,10 +379,10 @@ class TestDuplicateDeviceMerging: patch( f"{DISPLAY_MOD}.get_device_ports_from_topology", return_value={"R1": {"port": 5000, "node_type": "iou"}} ), - patch.object(ExecuteMultipleDeviceCommands, "_initialize_nornir", return_value=nornir), + patch.object(DeviceShowCommandRunner, "_initialize_nornir", return_value=nornir), patch(f"{DISPLAY_MOD}.filter_forbidden_commands", side_effect=fake_filter), ): - result = ExecuteMultipleDeviceCommands()._run( + result = DeviceShowCommandRunner().run( json.dumps( { "project_id": PROJECT_ID, @@ -368,11 +400,11 @@ class TestDuplicateDeviceMerging: def test_entry_without_device_name_fails_the_whole_batch(self): """An unaddressable entry must abort with an error, not vanish.""" - from gns3server.agent.gns3_copilot.tools_v2.display_tools_nornir import ( - ExecuteMultipleDeviceCommands, + from gns3server.agent.gns3_copilot.gns3_client.device_show_commands import ( + DeviceShowCommandRunner, ) - result = ExecuteMultipleDeviceCommands()._run( + result = DeviceShowCommandRunner().run( json.dumps( { "project_id": PROJECT_ID, diff --git a/tests/agent/mcp/test_tool_params.py b/tests/agent/mcp/test_tool_params.py index c56ba252c..bfa1afc1b 100644 --- a/tests/agent/mcp/test_tool_params.py +++ b/tests/agent/mcp/test_tool_params.py @@ -138,6 +138,17 @@ def _get_handler_params(handler_name): and sub.func.value.id in ("params", "params_data") ): return {"*"} + # Same for a handler that delegates the WHOLE params dict to a callee + # (e.g. device_config_send_handler → DeviceConfigCommandRunner().run()): + # the callee decides what to read, so the per-key check cannot see + # through it. isinstance(params, dict) is a type check, not a forward. + for sub in ast.walk(node): + if ( + isinstance(sub, ast.Call) + and not (isinstance(sub.func, ast.Name) and sub.func.id == "isinstance") + and any(isinstance(a, ast.Name) and a.id == "params" for a in sub.args) + ): + return {"*"} # Found the handler function, search for params.get("xxx") for sub in ast.walk(node): if not isinstance(sub, ast.Call): diff --git a/tests/agent/test_mcp_bridge.py b/tests/agent/test_mcp_bridge.py new file mode 100644 index 000000000..c3040bd2f --- /dev/null +++ b/tests/agent/test_mcp_bridge.py @@ -0,0 +1,196 @@ +# 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 . +# +# Copyright (C) 2025 Yue Guobin (岳国宾) +# Author: Yue Guobin (岳国宾) +# +# Project Home: https://github.com/yueguobin/gns3-copilot +# + +""" +Tests for the copilot ← MCP tool bridge (tools_v2/mcp_bridge.py). + +The bridge reuses the MCP server's tool registration as the single source +of truth for the copilot's LangChain tools. These tests pin the filter +(project-scoped allowlist, no administration tools), the drift guard on +requested names, the args-model generation, and the sync/async context +bridging. +""" + +import asyncio +import json +from typing import Any + +import pytest + +from gns3server.agent.gns3_copilot.tools_v2 import mcp_bridge +from gns3server.agent.gns3_copilot.tools_v2.mcp_bridge import ( + MCP_ALLOWED_TOOLS, + NATIVE_TOOL_NAMES, + _run_coro_sync, + _unwrap_mcp_content, + adapted_mcp_tools, +) + + +def test_allowlist_excludes_administration_tools() -> None: + """The copilot runs inside one project: management tools stay out.""" + banned = { + "project_list", + "project_create", + "project_delete", + "project_open", + "project_close", + "template_create", + "template_update", + "template_delete", + "compute_list", + "compute_get", + "appliance_list", + "appliance_install", + "image_list", + "image_delete", + "image_prune", + "server_version", + "server_statistics", + } + assert banned & MCP_ALLOWED_TOOLS == set() + + +def test_every_allowed_tool_exists_on_the_mcp_server() -> None: + """The allowlist must not reference tools the MCP server does not register.""" + from gns3server.agent.mcp import mcp + + registered = {tool.name for tool in mcp._tool_manager.list_tools()} + assert MCP_ALLOWED_TOOLS <= registered + + +def test_adapted_pool_is_allowlist_minus_native_shadows() -> None: + tools = adapted_mcp_tools() + names = {tool.name for tool in tools} + assert names == MCP_ALLOWED_TOOLS - NATIVE_TOOL_NAMES + # link_create is served by the copilot-native wrapper (port-name + # resolution) and must not be adapted. + assert "link_create" not in names + + +def test_adapted_subset_preserves_order_and_drift_guard() -> None: + tools = adapted_mcp_tools(names=["node_start", "node_stop"]) + assert [tool.name for tool in tools] == ["node_start", "node_stop"] + + with pytest.raises(RuntimeError, match="not available to the copilot"): + adapted_mcp_tools(names=["node_start", "no_such_tool"]) + + +def test_adapted_args_model_matches_mcp_schema() -> None: + tool = next(t for t in adapted_mcp_tools() if t.name == "node_create") + fields = tool.args_schema.model_fields + # required parameter carried over from the MCP JSON schema + assert "project_id" in fields + assert fields["project_id"].is_required() + # optional parameters keep their MCP defaults + assert fields["compute_id"].default == "local" + assert fields["x"].default == 0 + # **kwargs-style MCP tools surface a plain dict "kwargs" parameter + node_update = next(t for t in adapted_mcp_tools() if t.name == "node_update") + assert "kwargs" in node_update.args_schema.model_fields + + +def test_unwrap_mcp_content() -> None: + assert _unwrap_mcp_content([{"type": "text", "text": json.dumps({"a": 1})}]) == {"a": 1} + assert _unwrap_mcp_content([{"type": "text", "text": "plain text"}]) == "plain text" + assert _unwrap_mcp_content({"already": "a dict"}) == {"already": "a dict"} + assert _unwrap_mcp_content("bare string") == "bare string" + + +def test_run_coro_sync_without_running_loop() -> None: + async def value() -> int: + return 42 + + assert _run_coro_sync(value()) == 42 + + +def test_run_coro_sync_inside_running_loop() -> None: + """Sync tool code executing on the event loop thread must still work.""" + + async def value() -> int: + return 7 + + async def main() -> int: + return _run_coro_sync(value()) + + assert asyncio.run(main()) == 7 + + +class _FakeMcpTool: + """Minimal stand-in for an mcp.server.mcpserver Tool.""" + + name = "fake_probe" + description = "Fake tool for bridge tests." + parameters: dict[str, Any] = { + "properties": {"x": {"type": "integer", "description": "a number"}}, + "required": ["x"], + "type": "object", + } + + async def fn(self, x: int) -> list[dict[str, str]]: + # Report the contextvars the bridge was supposed to set, proving + # they survived the thread/loop hop into the handler context. + from gns3server.agent.mcp import _jwt_token_var, _jwt_token_version_var, _jwt_username_var + + return [ + { + "type": "text", + "text": json.dumps( + { + "x": x, + "token": _jwt_token_var.get(), + "username": _jwt_username_var.get(), + "token_version": _jwt_token_version_var.get(), + } + ), + } + ] + + +class _FakeTokenData: + username = "tester" + token_version = 3 + + +def test_invoke_bridges_copilot_context_into_mcp_handler(monkeypatch: pytest.MonkeyPatch) -> None: + """The copilot's JWT must reach the MCP contextvars inside the handler.""" + monkeypatch.setattr( + mcp_bridge, "build_gns3_ctx", lambda: {"jwt_token": "copilot-jwt", "server_url": "http://127.0.0.1:3080"} + ) + monkeypatch.setattr(mcp_bridge.auth_service, "get_token_data", lambda token: _FakeTokenData()) + + tool = mcp_bridge._adapt(_FakeMcpTool()) + result = tool.invoke({"x": 5}) + + assert result == {"x": 5, "token": "copilot-jwt", "username": "tester", "token_version": 3} + + +def test_invoke_without_token_returns_error(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(mcp_bridge, "build_gns3_ctx", lambda: None) + + tool = mcp_bridge._adapt(_FakeMcpTool()) + result = tool.invoke({"x": 5}) + + assert "error" in result