Commit 99c075fd authored by Andrea Sgambelluri's avatar Andrea Sgambelluri
Browse files

MCP server: expose the Optical Controller so P2MP services can be provisioned

The MCP server could only reach the NBI, so none of the Optical Controller's
P2MP / lightpath / RSA operations were callable, and provisioning an optical
service through the Service API needed two calls an agent had no way to know
about. 26 tools are added (90 total):

- Config/App/McpServer: resolve the Optical Controller's base URL the same way
  as the NBI's (TFS_OPTICAL_URL, else the injected opticalcontroller host/port)
  and add optical_request() alongside api_request().
- Base: OpticalControllerToolHandler, with optional trailing path segments for
  the controller's positional routes.
- Custom: tfs_provision_optical_service performs CreateService+UpdateService
  and rolls back if the second step fails, so an optical service is never left
  registered but unprovisioned; tfs_delete_optical_service repeats
  DeleteService until the service is gone, which an optical band requires.
- Definitions/Registry: P2MP compute/delete/recompute/get-active-paths, direct
  multi-lightpath add/delete, source addition, per-source subflow recompute,
  link-failure marking, point-to-point flexi-grid and multi-granular
  lightpaths, optical-band deletion, inspection and alarm subscriptions.

Three bugs this surfaced in the P2MP provisioning path:

- roadms.py: drop the 'band' leaf from media channels; the ROADMs reject it
  (bad-element) and the channel is already defined by its frequency range.
- OpticalConfig.py: P2MP settings carry no single center frequency, so
  'frequency' is present but None and UpdateOpticalConfig failed on int(None),
  leaving the ROADM media channels unrecorded.
- TaskExecutor/OCServiceHandler: pass bidir to deconfigure_optical_device_pmp,
  as the non-P2MP path already does; without it disable_media_channel stopped
  after the first channel and left the rest of a P2MP tree on the ROADMs.

Verified against the dummy P2MP topology (T1.1/T1.2/T1.3 -> R1 -> R2 -> T2.1):
all 26 tools exercised, P2MP service provisioned and deleted through the MCP
tools with the ROADM media channels created and fully torn down again, and no
device, service or context errors.

Co-Authored-By: default avatarClaude Opus 5 <noreply@anthropic.com>
parent 29476332
Loading
Loading
Loading
Loading
+34 −4
Changes for src/context/service/database/OpticalConfig.py: 34 added lines, 4 removed lines.
Original line number Diff line number Diff line
@@ -343,6 +343,35 @@ def set_opticalconfig(db_engine : Engine, request : OpticalConfig):
    opticalconfig_id = run_transaction(sessionmaker(bind=db_engine), callback)
    return {'opticalconfig_uuid': opticalconfig_id}

def _as_number(value):
    """Numeric value of an optical setting, or None when it is absent/not a number."""
    if value is None: return None
    try:
        return float(value)
    except (TypeError, ValueError):
        return None


def _channel_frequency_range(new_config : dict):
    """(lower_frequency, upper_frequency) of a media channel, in Hz.

    Taken from the explicit lower-/upper-frequency when the caller provides them, otherwise
    derived from a center frequency plus channel width. Point-to-multipoint (DSCM) settings
    carry no single center frequency -- each subcarrier group has its own -- so 'frequency'
    is present but None there; returns (0, 0) when no range can be determined rather than
    failing the whole optical-config update.
    """
    lower = _as_number(new_config.get('lower-frequency'))
    upper = _as_number(new_config.get('upper-frequency'))
    if lower is not None and upper is not None:
        return int(lower), int(upper)
    frequency = _as_number(new_config.get('frequency'))
    width = _as_number(new_config.get('band'))
    if frequency is None or width is None:
        return 0, 0
    return int(frequency - width / 2), int(frequency + width / 2)


def update_opticalconfig(db_engine : Engine, request : OpticalConfig):
    LOGGER.debug('[update_opticalconfig] received request: {:s}'.format(grpc_message_to_json_string(request)))

@@ -475,13 +504,14 @@ def update_opticalconfig(db_engine : Engine, request : OpticalConfig):
                            src_port, dest_port = flow
                            channel_index = flow_id + num
                            num += 1
                            lower_frequency, upper_frequency = _channel_frequency_range(config['new_config'])
                            channels.append({
                                # "opticalconfig_uuid":opticalconfig_uuid,
                                "roadm_uuid"          : roadm_get_uuid(device_id),
                                "channel_uuid"        : channel_get_uuid(f'media_channel_{channel_index}',device_uuid),
                                "band_name"           : config['new_config']['band_type'],
                                "lower_frequency"     : int(int(config['new_config']['frequency']) - (int(config['new_config']['band'])/2)) if "frequency" in config['new_config']  else 0,
                                "upper_frequency"     : int(int(config['new_config']['frequency']) + (int(config['new_config']['band'])/2)) if "frequency" in config['new_config']  else 0,
                                "lower_frequency"     : lower_frequency,
                                "upper_frequency"     : upper_frequency,
                                "dest_port"           : dest_port,
                                "src_port"            : src_port,
                                "status"              : config['new_config']["status"] if "status" in config['new_config'] else "",
@@ -508,8 +538,8 @@ def update_opticalconfig(db_engine : Engine, request : OpticalConfig):
                                "roadm_uuid"      : roadm_get_uuid(device_id),
                                "channel_uuid"    : channel_get_uuid(f'optical_bands_{channel_index}',device_uuid),
                                "band_name"       : config['new_config']['band_type'],
                                "lower_frequency" : int(config['new_config']["low-freq"]) if "low-freq" in config['new_config']  else 0,
                                "upper_frequency" : int(config['new_config']["up-freq"]) if "up-freq" in config['new_config']  else 0,
                                "lower_frequency" : int(_as_number(config['new_config'].get("low-freq")) or 0),
                                "upper_frequency" : int(_as_number(config['new_config'].get("up-freq")) or 0),
                                "dest_port"       : dest_port,
                                "src_port"        : src_port,
                                "status"          : config['new_config']["status"] if "status" in config['new_config'] else "",
+2 −1
Changes for src/device/service/drivers/oc_driver/templates/VPN/roadms.py: 2 added lines, 1 removed line.
Original line number Diff line number Diff line
@@ -29,7 +29,8 @@ def create_media_channel (resources):
    unwanted_keys=['destination_port','source_port','channel_namespace'
                ,'frequency','operational-mode','target-output-power',
               "handled_flow","channel_num",'bidir',
               'Band']   # requested optical-band width (P2MP settings), not a media-channel leaf
               'Band',   # requested optical-band width (P2MP settings), not a media-channel leaf
               'band']   # channel width; the channel is defined by lower-/upper-frequency

    bidir = next((i['value'] for i in resources if 'resource_key' in i and i['resource_key'] == 'bidir'), 1)
    config,ports,index=filter_config(resources,unwanted_keys)
+24 −1
Changes for src/mcp_server/Config.py: 24 added lines, 1 removed line.
Original line number Diff line number Diff line
@@ -13,9 +13,14 @@
# limitations under the License.

from common.Constants import ServiceNameEnum
from common.Settings import get_service_host, get_service_port_http, get_setting
from common.Settings import (
    get_service_host, get_service_port_grpc, get_service_port_http, get_setting
)

DEFAULT_API_PREFIX = "/tfs-api"
# The Optical Controller serves its HTTP API under this prefix, on the port registered for it in
# common.Constants (10060) -- the same convention service/service/tools/OpticalTools.py relies on.
DEFAULT_OPTICAL_PREFIX = "/OpticalTFS"
DEFAULT_MODE = "normal"
DEFAULT_TRANSPORT = "sse"

@@ -27,6 +32,8 @@ ENVVAR_TFS_NBI_URL = "TFS_NBI_URL"
ENVVAR_TFS_NBI_USER = "TFS_NBI_USER"
ENVVAR_TFS_NBI_PASS = "TFS_NBI_PASS"
ENVVAR_TFS_NBI_VERIFY_TLS = "TFS_NBI_VERIFY_TLS"
ENVVAR_TFS_OPTICAL_URL = "TFS_OPTICAL_URL"
ENVVAR_TFS_OPTICAL_PREFIX = "TFS_OPTICAL_PREFIX"


def get_mcp_server_port() -> int:
@@ -69,3 +76,19 @@ def get_tfs_nbi_pass() -> str:
def get_tfs_nbi_verify_tls() -> bool:
    value = get_setting(ENVVAR_TFS_NBI_VERIFY_TLS, default="false")
    return str(value).strip().lower() in {"1", "true", "yes", "on"}


def get_tfs_optical_url() -> str:
    """Base URL of the Optical Controller's HTTP API, resolved the same way as the NBI's:
    from TFS_OPTICAL_URL when set, otherwise from the host/port Kubernetes injects for the
    "opticalcontroller" Service, so the same image runs unmodified on any deployment."""
    api_url = get_setting(ENVVAR_TFS_OPTICAL_URL, default=None)
    if api_url:
        return api_url
    optical_host = get_service_host(ServiceNameEnum.OPTICALCONTROLLER)
    optical_port = get_service_port_grpc(ServiceNameEnum.OPTICALCONTROLLER)
    return "http://{:s}:{:d}".format(str(optical_host), int(optical_port))


def get_tfs_optical_prefix() -> str:
    return get_setting(ENVVAR_TFS_OPTICAL_PREFIX, default=DEFAULT_OPTICAL_PREFIX)
+10 −1
Changes for src/mcp_server/service/App.py: 10 added lines, 1 removed line.
Original line number Diff line number Diff line
@@ -24,7 +24,8 @@ from common.Settings import (
from mcp_server.Config import (
    get_mcp_server_mode, get_mcp_server_port, get_mcp_server_transport,
    get_mock_inventory_path, get_tfs_nbi_pass, get_tfs_nbi_prefix,
    get_tfs_nbi_url, get_tfs_nbi_user, get_tfs_nbi_verify_tls
    get_tfs_nbi_url, get_tfs_nbi_user, get_tfs_nbi_verify_tls,
    get_tfs_optical_prefix, get_tfs_optical_url
)

from .Dependencies import LOGGER
@@ -44,6 +45,12 @@ def parse_args():
    parser.add_argument("--api-prefix",
                        default=get_tfs_nbi_prefix(),
                        help="TFS NBI API URL prefix (default: /tfs-api)")
    parser.add_argument("--optical-url",
                        default=get_tfs_optical_url(),
                        help="Optical Controller base URL (default: service-discovered or $TFS_OPTICAL_URL)")
    parser.add_argument("--optical-prefix",
                        default=get_tfs_optical_prefix(),
                        help="Optical Controller API URL prefix (default: /OpticalTFS)")
    parser.add_argument("--mode", choices=["normal", "mocked-tfs"],
                        default=get_mcp_server_mode(),
                        help="Operational mode: normal or mocked-tfs (default: normal)")
@@ -71,6 +78,8 @@ def main():
        port=args.port,
        api_url=args.api_url,
        api_prefix=args.api_prefix,
        optical_url=args.optical_url,
        optical_prefix=args.optical_prefix,
        username=args.username,
        password=args.password,
        verify_tls=not args.insecure,
+38 −4
Changes for src/mcp_server/service/McpServer.py: 38 added lines, 4 removed lines.
Original line number Diff line number Diff line
@@ -43,6 +43,8 @@ class TfsMcpServer:
        port: int = 3002,
        api_url: str = "http://127.0.0.1:80",
        api_prefix: str = "/tfs-api",
        optical_url: Optional[str] = None,
        optical_prefix: str = "/OpticalTFS",
        username: Optional[str] = None,
        password: Optional[str] = None,
        verify_tls: bool = False,
@@ -60,6 +62,9 @@ class TfsMcpServer:
        self.port = port
        self.api_url = api_url.rstrip('/')
        self.api_prefix = '/' + api_prefix.strip('/')
        # Optical Controller API: P2MP / lightpath / RSA operations the NBI does not expose.
        self.optical_url = optical_url.rstrip('/') if optical_url else None
        self.optical_prefix = '/' + optical_prefix.strip('/') if optical_prefix else ''
        self.auth = (username, password) if username and password else None
        self.verify_tls = verify_tls

@@ -70,8 +75,9 @@ class TfsMcpServer:
        self._register_handlers()

        LOGGER.info(
            "TfsMcpServer initialized (mode=%s, transport=%s, port=%s, api_url=%s, prefix=%s)",
            self.mode, transport, port, self.api_url, self.api_prefix,
            "TfsMcpServer initialized (mode=%s, transport=%s, port=%s, api_url=%s, prefix=%s, "
            "optical_url=%s)",
            self.mode, transport, port, self.api_url, self.api_prefix, self.optical_url,
        )

    async def api_request(
@@ -82,10 +88,14 @@ class TfsMcpServer:
        json_data: Optional[Any] = None,
        timeout: float = 60.0,
        use_prefix: bool = True,
        base_url: Optional[str] = None,
        prefix: Optional[str] = None,
    ) -> Any:
        """Issue an HTTP request to the TFS NBI."""
        """Issue an HTTP request to the TFS NBI, or to another TFS API when base_url/prefix
        are given (see optical_request)."""
        if prefix is None:
            prefix = self.api_prefix if use_prefix else ''
        url = f"{self.api_url}{prefix}{endpoint}"
        url = f"{base_url or self.api_url}{prefix}{endpoint}"

        async with httpx.AsyncClient(timeout=timeout, verify=self.verify_tls, auth=self.auth) as client:
            try:
@@ -110,6 +120,30 @@ class TfsMcpServer:
            except Exception as error:  # pylint: disable=broad-except
                return {"error": str(error), "status": "error", "url": url}

    async def optical_request(
        self,
        method: str,
        endpoint: str,
        params: Optional[Dict] = None,
        json_data: Optional[Any] = None,
        timeout: float = 60.0,
    ) -> Any:
        """Issue an HTTP request to the Optical Controller's own API (P2MP path computation,
        lightpath provisioning, optical bands, alarm subscriptions). These operate on the
        controller's RSA state and are not reachable through the NBI."""
        if not self.optical_url:
            return {
                "status": "error",
                "error": (
                    "Optical Controller URL is not configured; set TFS_OPTICAL_URL or deploy the "
                    "opticalcontroller component so its host/port are discoverable."
                ),
            }
        return await self.api_request(
            method, endpoint, params=params, json_data=json_data, timeout=timeout,
            base_url=self.optical_url, prefix=self.optical_prefix,
        )

    @staticmethod
    def normalize_optical_slice_payload(slice_payload: Any) -> Any:
        """Ensure optical-slice payload has tapi-common:context.uuid.
Loading