mirror of
https://github.com/GNS3/gns3-server.git
synced 2026-11-25 07:04:34 +02:00
refactor(copilot): reuse MCP tools via a bridge; extract shared device runners
The copilot and the MCP service maintained two parallel wrapper layers (LangChain BaseTool classes vs @mcp.tool() functions) over the same handlers in gns3_client/api_handlers.py. Descriptions and parameters drifted apart (compute_id and link_type were missing on the copilot side). This makes the MCP registration the single source of truth and removes the duplicated wrappers. tools_v2/mcp_bridge.py adapts the MCP server's tool registration into LangChain tools: names, descriptions and argument schemas come from the MCP tools. The pool is filtered to project-scoped tools (MCP_ALLOWED_TOOLS) because the copilot runs inside one open project — project management, compute/appliance/image administration and server info tools stay out. The bridge carries the copilot's request JWT into the MCP contextvars (username/token_version decoded from the token so ticket-minting tools work) and runs the async MCP functions from the copilot's sync tool node on either thread flavor. Mode toolsets (teaching / lab_automation / troubleshooting_injection) are now composed from adapted MCP tools plus a few copilot-native ones that add value the MCP versions lack: link_create (port-name resolution), wait_seconds, packet_analysis(+skills), and the topology reader. Eight orphaned LangChain wrappers are deleted. The device command tools had the dependency inverted (the MCP handlers instantiated the copilot LangChain classes and round-tripped through JSON strings). The Nornir/Netmiko classes moved verbatim (git mv) into the shared layer as plain runners — DeviceConfigCommandRunner, DeviceShowCommandRunner, VpcsCommandRunner — with _run(json_string) becoming run(params, gns3_ctx). The optional Jinja2 template rendering moved from the MCP handlers into the runners (and into utils/device_configs.render_device_template), so both entry paths get it; the MCP handlers are now pure delegation. This also drops the json.dumps/json.loads detour the MCP path used to take. test_tool_params consistency gate extended: a handler that forwards the whole params dict to a callee is a wildcard (same rationale as the params.items() case) — the per-key check cannot see through delegation.
This commit is contained in:
34 files changed
+986
-2772
No files matched your search
@@ -1,6 +1,6 @@
|
||||
#
|
||||
# Copyright (C) 2026 GNS3 Technologies Inc.
|
||||
# Author: Yue Guobin
|
||||
# Author: YueGuobin
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
@@ -22,6 +22,10 @@ These tools connect to network device consoles via telnet/SSH and execute
|
||||
configuration or diagnostic commands. Device connection info is automatically
|
||||
discovered from the project topology using the device's tags for device_type.
|
||||
|
||||
The actual execution lives in the shared runners under
|
||||
``gns3_copilot/gns3_client/`` (plain classes, no LangChain): the MCP handlers
|
||||
below and the copilot (through the MCP tool bridge) call the same code.
|
||||
|
||||
Prerequisites:
|
||||
- Device must be started (use node_start / node_start_all)
|
||||
- Device must have a 'device_type:<type>' tag set in GNS3
|
||||
@@ -29,141 +33,23 @@ Prerequisites:
|
||||
- Device must have a console port assigned
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from jinja2 import Template as JinjaTemplate
|
||||
from jinja2 import TemplateError as JinjaError
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _render_template(template: str, device_configs: list[dict], commands_field: str = "config_commands") -> list[dict]:
|
||||
"""Render a Jinja2 template for each device's vars into the specified commands field.
|
||||
|
||||
Entries with the same device_name are merged into a single entry
|
||||
so they share one Nornir session and avoid output fragmentation.
|
||||
|
||||
Each device in device_configs can have:
|
||||
- "vars": dict of template variables (rendered into commands_field)
|
||||
- commands_field: existing commands merged after rendering if present
|
||||
|
||||
Args:
|
||||
commands_field: field name for the rendered commands, e.g. "config_commands", "commands"
|
||||
"""
|
||||
try:
|
||||
jinja = JinjaTemplate(template)
|
||||
except JinjaError as e:
|
||||
# a syntactically invalid template must not escape as a raw exception
|
||||
error_msg = f"Template rendering failed: {e}"
|
||||
log.error(error_msg)
|
||||
return [{"status": "failed", "error": error_msg}]
|
||||
merged: dict[str, dict] = {}
|
||||
for dev in device_configs:
|
||||
name = dev.get("device_name")
|
||||
if not name:
|
||||
continue
|
||||
vars_data = dev.get("vars", {})
|
||||
if name not in merged:
|
||||
merged[name] = {"device_name": name, commands_field: list(dev.get(commands_field, []))}
|
||||
entry = merged[name]
|
||||
if vars_data:
|
||||
try:
|
||||
output = jinja.render(**vars_data)
|
||||
lines = [l for l in output.splitlines() if l.strip()]
|
||||
entry[commands_field].extend(lines)
|
||||
except JinjaError as e:
|
||||
error_msg = f"Template rendering failed for '{name}': {e}"
|
||||
log.error(error_msg)
|
||||
return [{"status": "failed", "error": error_msg}]
|
||||
return list(merged.values())
|
||||
|
||||
|
||||
# ── Tool handlers ──────────────────────────────────────────────────────────
|
||||
from gns3server.agent.gns3_copilot.gns3_client.device_config_commands import DeviceConfigCommandRunner
|
||||
from gns3server.agent.gns3_copilot.gns3_client.device_show_commands import DeviceShowCommandRunner
|
||||
from gns3server.agent.gns3_copilot.gns3_client.vpcs_commands import VpcsCommandRunner
|
||||
|
||||
|
||||
def device_config_send_handler(params: dict[str, Any], gns3_ctx: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""Send configuration commands to network devices via console."""
|
||||
project_id = params.get("project_id")
|
||||
device_configs = params.get("device_configs")
|
||||
template = params.get("template")
|
||||
if not project_id or not device_configs:
|
||||
return [{"status": "failed", "error": "project_id and device_configs are required"}]
|
||||
|
||||
if template:
|
||||
device_configs = _render_template(template, device_configs, commands_field="config_commands")
|
||||
if len(device_configs) == 1 and "error" in device_configs[0]:
|
||||
return device_configs
|
||||
|
||||
from gns3server.agent.gns3_copilot.tools_v2.config_tools_nornir import ExecuteMultipleDeviceConfigCommands
|
||||
|
||||
tool = ExecuteMultipleDeviceConfigCommands()
|
||||
input_data = json.dumps(
|
||||
{
|
||||
"project_id": project_id,
|
||||
"device_configs": device_configs,
|
||||
}
|
||||
)
|
||||
return tool._run(
|
||||
input_data,
|
||||
jwt_token=gns3_ctx["jwt_token"],
|
||||
url=gns3_ctx["server_url"],
|
||||
)
|
||||
return DeviceConfigCommandRunner().run(params, gns3_ctx)
|
||||
|
||||
|
||||
def device_show_run_handler(params: dict[str, Any], gns3_ctx: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""Run read-only diagnostic (show) commands on network devices."""
|
||||
project_id = params.get("project_id")
|
||||
device_configs = params.get("device_configs")
|
||||
template = params.get("template")
|
||||
if not project_id or not device_configs:
|
||||
return [
|
||||
{
|
||||
"status": "failed",
|
||||
"error": "project_id and device_configs (list of {device_name, commands}) are required",
|
||||
}
|
||||
]
|
||||
|
||||
if template:
|
||||
device_configs = _render_template(template, device_configs, commands_field="commands")
|
||||
if len(device_configs) == 1 and "error" in device_configs[0]:
|
||||
return device_configs
|
||||
|
||||
from gns3server.agent.gns3_copilot.tools_v2.display_tools_nornir import ExecuteMultipleDeviceCommands
|
||||
|
||||
tool = ExecuteMultipleDeviceCommands()
|
||||
input_data = json.dumps(
|
||||
{
|
||||
"project_id": project_id,
|
||||
"device_configs": device_configs,
|
||||
}
|
||||
)
|
||||
return tool._run(
|
||||
input_data,
|
||||
jwt_token=gns3_ctx["jwt_token"],
|
||||
url=gns3_ctx["server_url"],
|
||||
)
|
||||
return DeviceShowCommandRunner().run(params, gns3_ctx)
|
||||
|
||||
|
||||
def vpcs_config_set_handler(params: dict[str, Any], gns3_ctx: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""Configure VPCS devices (set IP, gateway, etc.)."""
|
||||
project_id = params.get("project_id")
|
||||
device_configs = params.get("device_configs")
|
||||
if not project_id or not device_configs:
|
||||
return [{"status": "failed", "error": "project_id and device_configs are required"}]
|
||||
|
||||
from gns3server.agent.gns3_copilot.tools_v2.vpcs_tools_netmiko import VPCSCommands
|
||||
|
||||
tool = VPCSCommands()
|
||||
input_data = json.dumps(
|
||||
{
|
||||
"project_id": project_id,
|
||||
"device_configs": device_configs,
|
||||
}
|
||||
)
|
||||
return tool._run(
|
||||
input_data,
|
||||
jwt_token=gns3_ctx["jwt_token"],
|
||||
url=gns3_ctx["server_url"],
|
||||
)
|
||||
return VpcsCommandRunner().run(params, gns3_ctx)
|
||||
Reference in new issue
Block a user