Metadata-Version: 2.4
Name: fiber-ac-mcp
Version: 1.4.0
Summary: FIBER — Optical operations platform MCP server for AI datacenters (gNMI telemetry, ML predictions, Digital Twin, NCCL-optical correlation, SPARQL semantic queries). Dual runtime: mcp python-sdk 1.x by default, 2.x via an explicit SDK override.
Author-email: Satoshi Holdings <contact@fiber.ac>
Maintainer-email: Satoshi Holdings <contact@fiber.ac>
License: MIT
Project-URL: Homepage, https://fiber.ac
Project-URL: Documentation, https://api.fiber.ac/docs
Keywords: mcp,model-context-protocol,optical-networking,gnmi,ai-datacenter,cpo,lpo,400zr,coherent,nccl,digital-twin,observability,conformal-prediction,deterministic-network-query,rbac
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: System Administrators
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: System :: Monitoring
Classifier: Topic :: System :: Networking :: Monitoring
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: mcp<2,>=1.0.0
Requires-Dist: httpx>=0.27.0

# FIBER MCP Server

<!-- MCP Registry ownership verification (required by registry.modelcontextprotocol.io) -->
mcp-name: io.github.superlabs-x/fiber

Model Context Protocol (MCP) server for the **FIBER AI Infrastructure Reliability Platform**.

Exposes 36 curated FIBER endpoints as MCP tools (+ 4 write tools behind a flag) so Claude Code / Cursor / Claude Desktop / VS Code Copilot can query optical telemetry, run Digital Twin what-if scenarios, fetch ML predictions, and generate postmortems — directly from developer IDEs.

**Version 1.4.0** — dual runtime: the same server runs on **mcp python-sdk 1.x and 2.x**.

> **Package name changed (1.4.0).** The package is now **`fiber-ac-mcp`** (Registry: `io.github.superlabs-x/fiber`), published by the FIBER team from CI. The older `fiber-mcp` package (≤ 1.1.0) is no longer updated — uninstall it and install `fiber-ac-mcp`.
> 1.4.0 also rejects path-like tool arguments, masks nested secrets in the audit log, records failed API calls as errors, and no longer ships a default API key.

## Why MCP?

Until now, using FIBER meant opening the dashboard or calling the REST API. With MCP, your AI assistant just… knows.

```
User (in Claude Code): "leaf-010 Ethernet1/43 의 72시간 RUL 어떻게 돼?"

Claude  → calls tool: fiber_ml_predict_rul(switch_name="leaf-010", port_name="Ethernet1/43")
         → returns: {"rul_hours": 0.01, "urgency": "imminent", "val_mae_hours": 2.99}

Claude (to user): "LSTM 모델이 잔존 수명을 0.01시간으로 예측합니다 —
                 즉시 교체 필요 (urgency: imminent). 모델 검증 MAE는 2.99h입니다."
```

## Dual runtime (v1.3.0)

The mcp python-sdk 2.x line is a breaking rewrite of the server API. Rather than pick a
side, the package splits into an SDK-agnostic core plus one thin adapter per SDK major —
so tool names, JSON schemas, results and governance are identical on both.

| File | Role | Needs |
|---|---|---|
| `fiber_mcp_core.py` | Tool catalog (plain dicts), FIBER REST dispatch, governance (allowlist / audit / role hints). **Imports no `mcp` module at all.** | `httpx` |
| `fiber_mcp_server.py` | **1.x adapter** — low-level `Server` + `@server.list_tools()` / `@server.call_tool()` decorators, stdio | `mcp>=1.0.0,<2` |
| `fiber_mcp_v2.py` | **2.x adapter** — `Server(on_list_tools=…, on_call_tool=…)` constructor params returning `ListToolsResult` / `CallToolResult`, stdio | `mcp>=2.1,<3` |
| `fiber_mcp.py` | Entry point — reads the installed distribution metadata and dispatches to the matching adapter | either |
| `hf_space/app.py` | Gradio `mcp_server=True` front for a read-only subset, delegating to the same core | `gradio[mcp]` |

```bash
# default — mcp 1.x → fiber_mcp_server
pip install fiber-ac-mcp

# opt-in — mcp 2.x → fiber_mcp_v2 (explicit SDK override)
pip install --no-deps fiber-ac-mcp && pip install 'mcp>=2.1,<3' 'httpx>=0.27.0'
# or, over an existing install:  pip install -U 'mcp>=2.1,<3'
# Either way pip prints one dependency-conflict notice against the mcp<2 pin
# ("fiber-mcp 1.3.0 requires mcp<2,>=1.0.0, but you have mcp 2.1.1"). That notice is
# expected — the runtime is fine, and fiber_mcp.py switches adapters on it.

fiber-mcp-server   # auto-selects the adapter for the installed SDK
fiber-mcp-v2       # forces the 2.x adapter
```

The **default dependency stays `mcp>=1.0.0,<2`** on purpose: `mcp>=1.28` pulls
`sse-starlette 3` → `starlette 1.x`, which conflicts with the FastAPI 0.115 pin the FIBER
API and the repo test image use.

> **Why 2.x is an install-time override and not a `[…]` extra.** Extras are *additive* to
> the base dependencies, so an extra requiring `mcp>=2.1` can never coexist with a base pin
> of `mcp<2` — pip fails with `ResolutionImpossible` naming both. Putting an
> `extra != "…"` marker on the base requirement does not help either: pip evaluates the base
> candidate a second time without extras. And an extra literally named `v2` is worse still —
> `v2` is a valid PEP 440 version (the `v` prefix), so the marker `extra == "v2"` makes pip
> 25.x's vendored `packaging` attempt a version comparison and raise `InvalidVersion: ''`,
> breaking even a plain `pip install fiber-mcp` with no extras (fixed in pip 26.2; all
> reproduced on pip 25.0.1, the python:3.12-slim default). Hence the two-step install above.

### What changed in mcp python-sdk 2.x

| 1.x | 2.x |
|---|---|
| `@server.list_tools()` / `@server.call_tool()` decorators | handlers passed as `on_list_tools=` / `on_call_tool=` constructor params |
| handler args `(name, arguments)`, returns `list[TextContent]` | handler args `(ctx, params)`, returns `CallToolResult` / `ListToolsResult` |
| `FastMCP` (`mcp.server.fastmcp`) | `MCPServer` (`mcp.server.mcpserver`) |
| `mcp.types.Tool(inputSchema=…)` | field renamed `input_schema`; `inputSchema` still accepted as its alias (so one dict feeds both) |
| `create_connected_server_and_client_session` test helper | `mcp.Client(server)` — an in-process client that takes a `Server` instance directly |

Verified against **mcp 2.1.1** (`tests/test_mcp_v2.py` drives the real 2.x in-process client).

### MCP spec 2026-07-28 notes

* **Stateless handshake** — `initialize` and `Mcp-Session-Id` are gone; servers advertise
  through `server/discover`. FIBER holds no per-session state (every tool is a stateless
  REST read), so nothing in this server depended on the removed session identity. The SDK's
  `Server.run()` speaks both the modern and the legacy handshake.
* **MRTR `input_required`** — supported by the 2.x SDK. FIBER tools are single-shot and
  never return it today; a future interactive flow (e.g. confirming an RMA before writing)
  is the natural first use.
* **Roots / Sampling / Logging deprecated** (12-month window) — this server uses none of
  them, so no migration work is pending.

## Tools (36 read + 4 write)

| Category | Tools |
|---|---|
| Discovery | `fiber_health`, `fiber_info`, `fiber_cluster_overview`, `fiber_list_ports`, `fiber_port_detail_history`, `fiber_list_alerts`, `fiber_top_risky_ports` |
| ML | `fiber_ml_rul_info`, `fiber_ml_predict_rul`, `fiber_ml_anomaly_scan`, `fiber_ml_anomaly_conformal`, `fiber_ml_rul_with_heatmap` |
| CPO | `fiber_cpo_bank_status` |
| Digital Twin | `fiber_simulate_link_failure`, `fiber_digital_twin_monte_carlo`, `fiber_digital_twin_compare`, `fiber_digital_twin_deterministic_trace` |
| Counterfactual | `fiber_counterfactual_port`, `fiber_counterfactual_cluster` |
| NCCL | `fiber_nccl_summary`, `fiber_nccl_optical_correlation` |
| Integrations | `fiber_integrations_status`, `fiber_gcm_summary`, `fiber_gcm_optical_correlation`, `fiber_dcgm_correlation` |
| Benchmark | `fiber_run_benchmark_harness` |
| Sustainability | `fiber_sustainability`, `fiber_checkpoint_aware_windows` |
| Diagnosis | `fiber_list_diagnosis_reports`, `fiber_get_diagnosis_report`, `fiber_postmortem_timeline`, `fiber_postmortem_gala` |
| Semantic (SPARQL) | `fiber_sparql_query`, `fiber_topology_traverse`, `fiber_semantic_search` |
| Governance | `fiber_governance_status` |
| **Write (optional)** | `fiber_trigger_demo_scenario`, `fiber_ingest_nccl_events`, `fiber_create_rma`, `fiber_ingest_gcm_events` |

**Safety model**: all tools are read-only by default. Write tools only activate when `FIBER_ENABLE_WRITE=1` env var is set. The server uses the same API key / RBAC as the underlying FIBER REST API, so giving an MCP client a `viewer`-role key is strictly safer than handing out admin credentials.

## Governance

Three controls, all enforced inside `fiber_mcp_core` and therefore identical on both runtimes:

* **Tool allowlist** — `FIBER_MCP_TOOLS_ALLOWLIST` (CSV). Enforced when listing **and at call
  time**: a tool hidden from `tools/list` and then invoked by name is denied, not executed
  (the v1.0.2 enforcement gap, closed in v1.2.0).
* **Audit trail** — one JSONL line per call to `FIBER_MCP_AUDIT_LOG`
  (default `~/.fiber-mcp/audit.jsonl`, `off` disables):
  `{ts, tool, status, duration_ms, args, write_enabled}` where `status` is
  `ok | error | denied_allowlist | denied_write` and argument values matching
  key/password/token/secret/credential are replaced with `***`.
* **RBAC hints** — `TOOL_ROLE_HINT` maps each tool to the FIBER REST role it needs
  (`public` / `read` / `write` / `admin` / `diagnosis`), so an operator can pick the least
  privileged key per assistant. Call `fiber_governance_status` to see the live picture
  (exposed tools, allowlist state, audit path, adapter in use, SDK version).

## Install

### Quick
```bash
./setup.sh
```

### Manual
```bash
python3 -m venv ~/.fiber-mcp-venv
source ~/.fiber-mcp-venv/bin/activate
pip install -r requirements.txt          # mcp 1.x
# or, for the 2.x runtime:
pip install 'mcp>=2.1,<3' 'httpx>=0.27.0'
```

## Configure

### Claude Desktop

Edit `~/Library/Application Support/Claude/claude_desktop_config.json` (macOS) or `%APPDATA%\Claude\claude_desktop_config.json` (Windows):

```json
{
  "mcpServers": {
    "fiber": {
      "command": "/Users/you/.fiber-mcp-venv/bin/python3",
      "args": ["/path/to/hikari/sdks/mcp/fiber_mcp.py"],
      "env": {
        "FIBER_API_URL": "https://api.fiber.ac",
        "FIBER_API_KEY": "your-key-here",
        "FIBER_ENABLE_WRITE": "0"
      }
    }
  }
}
```

`fiber_mcp.py` auto-selects the adapter. Point `args` at `fiber_mcp_server.py` (1.x) or
`fiber_mcp_v2.py` (2.x) to pin one explicitly.

Restart Claude Desktop. In a new conversation ask: *"What's FIBER's current cluster overview?"* — Claude should call `fiber_cluster_overview` and respond with live data.

### Claude Code (CLI)

Claude Code auto-discovers MCP servers configured in `~/.claude/mcp_servers.json`:

```json
{
  "fiber": {
    "command": "python3",
    "args": ["/path/to/fiber_mcp.py"],
    "env": {
      "FIBER_API_URL": "https://api.fiber.ac",
      "FIBER_API_KEY": "your-key"
    }
  }
}
```

### Cursor

Cursor follows the same MCP spec. Add the server under *Settings → MCP → Edit Config*.

## Test locally with MCP Inspector

```bash
npx -y @modelcontextprotocol/inspector python3 fiber_mcp.py
```

Opens a web UI where you can list tools and invoke them interactively.

## Environment variables

| Variable | Default | Purpose |
|---|---|---|
| `FIBER_API_URL` | `https://api.fiber.ac` | Base URL of your FIBER deployment |
| `FIBER_API_KEY` | *(none — required)* | Bearer token; a viewer key is enough for the read tools |
| `FIBER_ENABLE_WRITE` | `0` | Set to `1` to expose the 4 write tools |
| `FIBER_MCP_TOOLS_ALLOWLIST` | *(empty)* | CSV of tool names; enforced on list **and** call |
| `FIBER_MCP_AUDIT_LOG` | `~/.fiber-mcp/audit.jsonl` | JSONL audit trail path, or `off` |
| `FIBER_HTTP_TIMEOUT` | `30` | Per-request seconds |

## On-premises / air-gapped deployments

The server talks to exactly one host — your FIBER deployment — and to nothing else. There
is no telemetry, no phone-home, and no third-party SaaS in the path.

* **Self-hosted FIBER**: set `FIBER_API_URL=http://fiber-api.internal:8000`. Nothing else
  changes; every tool is a call against that base URL.
* **Air-gapped install**: `pip download fiber-ac-mcp httpx mcp` on a connected host, move the
  wheels in, `pip install --no-index --find-links ./wheels fiber-ac-mcp`. The server itself
  needs no model, no GPU and no outbound DNS.
* **Proxies / mTLS / custom CAs**: call `fiber_mcp_core.set_http_client(httpx.AsyncClient(...))`
  from a wrapper before starting the server to inject your own transport, verify bundle or
  client certificate — the adapters and every tool then use it.
* **Audit retention**: `FIBER_MCP_AUDIT_LOG` is a plain append-only JSONL file; point it at
  a path your log shipper already collects. Sensitive argument values are redacted before
  the line is written.
* **Least privilege**: pair a `viewer` FIBER key with `FIBER_MCP_TOOLS_ALLOWLIST` to give an
  autonomous agent exactly the tools its runbook needs.

## RBAC hints

- For AI assistants on an engineer's laptop, create a **`viewer`** role API key. All 36 read tools work; no accidental mutations.
- For an autonomous agent (e.g., oncall runbook runner), use **`operator`** + `FIBER_ENABLE_WRITE=1`.
- For demo environments, pair `admin` + `FIBER_ENABLE_WRITE=1` to unlock `fiber_trigger_demo_scenario`.

## User flow examples

Natural-language queries your AI assistant now handles:

- "How many CPO banks are in critical state?"
- "Show me the top 10 risky ports by risk score"
- "If we lose all 10 spine uplinks of leaf-010, how many GPUs go offline?"
- "Run the benchmark harness with seed 42 and summarize"
- "What's the checkpoint-aware maintenance window for the next 6 hours?"
- "Correlate NCCL bandwidth drops with optical anomalies over the last 15 minutes"
- "Generate a postmortem timeline for leaf-039 Ethernet1/43 covering the past 24h"

## Architecture

```
 Claude Code / Cursor / Claude Desktop / Gradio Space
              │
              │  MCP stdio (JSON-RPC)
              ▼
 ┌──────────────────────────────────────────────┐
 │  fiber_mcp.py  (auto-select by SDK major)    │
 │      ├── fiber_mcp_server.py   mcp 1.x       │
 │      └── fiber_mcp_v2.py       mcp 2.x       │
 │              ↓ both import ↓                 │
 │  fiber_mcp_core.py                           │
 │    40 tool defs · REST dispatch · governance │
 └────────────────────┬─────────────────────────┘
                      │  HTTPS Bearer auth
                      ▼
 ┌──────────────────────────┐
 │  https://api.fiber.ac    │ ── FIBER FastAPI (~45 endpoints)
 │  or localhost:8000       │
 └──────────────────────────┘
```

## Status

- Curated 40 tools (36 read + 4 write)
- Dual runtime — mcp python-sdk 1.x and 2.x, one shared core
- stdio transport (SSE / streamable-HTTP for remote use planned)
- Read-only by default; write tools guarded by env var
- Call-time allowlist enforcement + JSONL audit trail
- Verified with `@modelcontextprotocol/inspector` and `tests/test_mcp_governance.py` (1.x) / `tests/test_mcp_v2.py` (2.x)

## Roadmap

- Streamable-HTTP endpoint for cloud deployment (stateless, per spec 2026-07-28)
- OAuth device flow (replace long-lived API keys)
- MRTR `input_required` confirmation step for write tools
- GraphQL subscription tool (live port updates)

## License

Same as FIBER — see repo root.
