Files
syncthing-blade-mcp/src/syncthing_mcp/registry.py
T
Claude 41f1018477 Token-efficient output, SKILL.md, Cloudflare Tunnel, new tools (v0.3.0)
Major improvements following best-in-class MCP patterns:

- Token efficiency: new formatters.py with compact JSON (no indent),
  short device IDs, character-limit truncation; all read tools gain
  concise=true (default) / concise=false toggle via ReadParams base
- Models: ReadParams/WriteParams hierarchy replaces flat models;
  backward-compatible aliases preserved for tests
- New tools: syncthing_remote_need (debug remote sync gaps),
  syncthing_device_stats (per-device statistics)
- SKILL.md: LLM skill guide with token rules, quick-start table,
  workflows, tool reference, and troubleshooting
- Cloudflare Tunnel: docker-compose.tunnel.yml for zero-trust HTTP
  deployment alongside existing Traefik/ACME support
- Fix duplicate dependencies in pyproject.toml; bump to v0.3.0

https://claude.ai/code/session_018efEinU8ypT2jHeex6o9PC
2026-02-17 03:44:48 +00:00

84 lines
2.9 KiB
Python

"""Instance registry — load Syncthing instances from environment variables."""
import json
import os
from syncthing_mcp.client import SyncthingClient
def format_bytes(n: int) -> str:
"""Human-readable byte size. Delegates to formatters.format_bytes."""
from syncthing_mcp.formatters import format_bytes as _fb
return _fb(n)
def load_instances() -> dict[str, SyncthingClient]:
"""Build instance registry from environment variables.
Supports two modes:
- Multi-instance via SYNCTHING_INSTANCES (JSON object)
- Single-instance via SYNCTHING_API_KEY + SYNCTHING_URL
"""
instances_json = os.environ.get("SYNCTHING_INSTANCES", "").strip()
if instances_json:
try:
cfg = json.loads(instances_json)
except json.JSONDecodeError as exc:
raise ValueError(f"Invalid SYNCTHING_INSTANCES JSON: {exc}") from exc
if not isinstance(cfg, dict) or not cfg:
raise ValueError("SYNCTHING_INSTANCES must be a non-empty JSON object.")
instances: dict[str, SyncthingClient] = {}
for name, entry in cfg.items():
if not isinstance(entry, dict):
raise ValueError(f"Instance '{name}' config must be a JSON object.")
url = entry.get("url", "http://localhost:8384")
api_key = entry.get("api_key", "")
instances[name] = SyncthingClient(name, url, api_key)
return instances
# Backward-compatible single-instance fallback
url = os.environ.get("SYNCTHING_URL", "http://localhost:8384")
api_key = os.environ.get("SYNCTHING_API_KEY", "")
return {"default": SyncthingClient("default", url, api_key)}
# Module-level registry, initialised at import time.
_instances: dict[str, SyncthingClient] = load_instances()
def get_instance(instance: str | None = None) -> SyncthingClient:
"""Resolve an instance by name, or auto-select when there is only one."""
if instance is None:
if len(_instances) == 1:
return next(iter(_instances.values()))
names = list(_instances.keys())
raise ValueError(
f"Multiple instances configured ({names}). "
"Specify 'instance' parameter to choose one."
)
if instance not in _instances:
raise ValueError(
f"Instance '{instance}' not found. Available: {list(_instances.keys())}"
)
return _instances[instance]
def get_all_instances() -> dict[str, SyncthingClient]:
"""Return the full instance registry."""
return _instances
def handle_error_global(e: Exception) -> str:
"""Fallback error handler when instance cannot be determined."""
if isinstance(e, ValueError):
return f"Error: {e}"
return f"Error: {type(e).__name__}: {e}"
def reload_instances() -> None:
"""Re-read environment and rebuild the instance registry (for testing)."""
global _instances
_instances = load_instances()