DD-338 A.2.dom.c — domain_hint patterns + per-record _meta.domain_hints

New per-blade lib (src/syncthing_mcp/domain_hint.py, ~155 LOC) implementing
the shared DD-338 Pattern engine: equals / contains / glob ops, first-match-
wins, YAML pattern loading with graceful degradation (Convention #22).

Server module gains a BladeConfigStore reader honouring STALLARI_STATE_ROOT
override + the sanitized blade-id directory layout the Swift writer ships
(Convention #23 reader-side compliance), plus a polymorphic Syncthing field
projector covering both folder records (id/label/path/type) and device
records (deviceID/name/addresses).

Wired into the two list-returning read tools:
  - syncthing_list_folders (instances.py — newly gains _meta envelope; was
    previously bare fmt(); start time now tracked for latency_ms)
  - syncthing_list_devices (devices.py — extends existing envelope with
    domain_hints kwarg)

formatters.{meta_envelope,append_meta} extended with an optional
domain_hints kwarg; key omitted from the JSON tail when empty / None.

stallari-plugin.yaml gains a blade_domain_hint_patterns: { patterns: [] }
block (0 defaults; users layer their own via the Settings → Blade Domain
Hints editor). No tools[] block exists in this manifest — per-tool
domain_scope flips land in the catalog mirror at stallari-plugins/plugins/
in a separate parent-session action.

pyyaml>=6.0 added to runtime dependencies (gated by ImportError inside
load_patterns_from_yaml so the blade still boots if the wheel is absent).
Version bump 0.5.0 → 0.6.0 (minor — new substrate capability).

Tests: 13 new cases in tests/test_domain_hint.py covering empty-patterns,
folder+device matches, first-match-wins, glob wildcards, unknown-field
projector handoff, YAML well-formed / partial / malformed / non-mapping
root / missing-patterns-key. Full suite 133/133 green.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
PiersandClaude Opus 4.7 committed 2026-05-23 12:46:47 +10:00
1 parent d3e364a18f
commit 06217b6fdc
9 files changed
+571 -8

No files matched your search

+155
View File
@@ -0,0 +1,155 @@
"""DD-338 A.2.dom — per-record domain hint computation.
Pattern engine consumed by tool modules to annotate per-record results with
a ``domain_hints: {record_id: domain}`` entry in the ``_meta`` envelope.
First-match-wins over a user-defined pattern list. Patterns live in the
BladeConfigStore (Convention #23) at::
<state-root>/blade-config/syncthing-blade-mcp/config.yaml
The YAML shape::
patterns:
- field: path
op: contains
value: "/Family/"
domain: family
- field: label
op: glob
value: "Work*"
domain: work
- field: deviceID
op: equals
value: ABCDEFG-...
domain: ops
Empty / missing / malformed config ⇒ empty pattern list ⇒ no
``domain_hints`` key emitted (Convention #22 graceful degradation).
"""
from __future__ import annotations
import fnmatch
import logging
from collections.abc import Callable
from dataclasses import dataclass
from typing import Any
logger = logging.getLogger(__name__)
@dataclass(frozen=True)
class Pattern:
"""A single domain-hint matching rule.
Attributes:
field: Logical field name (e.g. ``path``, ``label``, ``deviceID``);
resolved by the per-blade ``field_projector`` callable into the
record's actual storage shape.
op: One of ``equals`` | ``contains`` | ``glob``.
value: Comparison value (always coerced to string; lists are matched
element-wise).
domain: Domain string to emit on match (e.g. ``family``, ``work``).
"""
field: str
op: str
value: str
domain: str
_VALID_OPS = frozenset({"equals", "contains", "glob"})
def compute_domain_hint(
record: dict[str, Any],
patterns: list[Pattern],
field_projector: Callable[[dict[str, Any], str], Any],
) -> str | None:
"""Compute the domain hint for a single record.
First-match-wins over ``patterns``. Returns ``None`` when no pattern
matches, the record lacks the projected field, or the pattern list is
empty.
The projector may return:
- ``None`` (field absent ⇒ no match)
- a scalar (compared directly)
- a list of scalars or dicts (each element compared; dicts coerced
to empty string ⇒ no match unless ``value=""``)
"""
if not patterns:
return None
for pattern in patterns:
if pattern.op not in _VALID_OPS:
# Unknown op silently skipped — defensive against future schema drift.
continue
rec_val = field_projector(record, pattern.field)
if rec_val is None:
continue
candidates: list[Any] = rec_val if isinstance(rec_val, list) else [rec_val]
for c in candidates:
if isinstance(c, dict):
# Dict candidates cannot be matched without further projection;
# callers should project to a string inside the projector.
continue
s = str(c)
if pattern.op == "equals":
if s == pattern.value:
return pattern.domain
elif pattern.op == "contains":
if pattern.value in s:
return pattern.domain
elif pattern.op == "glob":
if fnmatch.fnmatchcase(s, pattern.value):
return pattern.domain
return None
def load_patterns_from_yaml(yaml_str: str) -> list[Pattern]:
"""Parse a YAML config string into a list of ``Pattern``.
Returns ``[]`` on any of:
- empty input
- YAML parse error
- non-mapping root
- ``patterns`` key missing or non-list
- per-pattern missing required keys / type errors
Per-pattern parse failures are silently skipped (not fatal) — partial
configs still load their good entries.
"""
if not yaml_str.strip():
return []
try:
import yaml # type: ignore[import-untyped]
except ImportError:
logger.warning("pyyaml not installed; domain_hint patterns disabled")
return []
try:
data = yaml.safe_load(yaml_str)
except yaml.YAMLError as e:
logger.warning("blade-config YAML parse error: %s", e)
return []
if not data or not isinstance(data, dict):
return []
raw_patterns = data.get("patterns", [])
if not isinstance(raw_patterns, list):
return []
result: list[Pattern] = []
for p in raw_patterns:
if not isinstance(p, dict):
continue
try:
result.append(
Pattern(
field=str(p["field"]),
op=str(p["op"]),
value=str(p["value"]),
domain=str(p["domain"]),
)
)
except (KeyError, TypeError):
continue
return result
+10 -1
View File
@@ -52,21 +52,28 @@ def meta_envelope(
filtered_by: list[str] | None = None,
redactions: list[str] | None = None,
latency_ms: int,
domain_hints: dict[str, str] | None = None,
) -> str:
"""Render the canonical JSON-tail _meta envelope line.
Returns the literal line ``_meta: {"matched_total": ..., ...}`` — caller
is responsible for joining it to the payload with ``\\n\\n``.
DD-338 A.2.dom.c — when ``domain_hints`` is non-empty, an additional
``domain_hints: {record_id: domain}`` entry is emitted. Empty / None ⇒
key omitted entirely (Convention #22 graceful degradation).
"""
fb = sorted(filtered_by) if filtered_by else []
rd = list(redactions) if redactions else []
payload = {
payload: dict[str, Any] = {
"matched_total": matched_total,
"returned": returned,
"filtered_by": fb,
"redactions": rd,
"latency_ms": latency_ms,
}
if domain_hints:
payload["domain_hints"] = domain_hints
return "_meta: " + json.dumps(payload, separators=(",", ":"))
@@ -78,6 +85,7 @@ def append_meta(
filtered_by: list[str] | None = None,
redactions: list[str] | None = None,
latency_ms: int,
domain_hints: dict[str, str] | None = None,
) -> str:
"""Append the _meta envelope tail line to a serialized payload."""
return payload + "\n\n" + meta_envelope(
@@ -86,6 +94,7 @@ def append_meta(
filtered_by=filtered_by,
redactions=redactions,
latency_ms=latency_ms,
domain_hints=domain_hints,
)
+140
View File
@@ -1,14 +1,154 @@
"""FastMCP server creation and lifespan."""
import os
from contextlib import asynccontextmanager
from typing import Any
from mcp.server.fastmcp import FastMCP
from starlette.requests import Request
from starlette.responses import JSONResponse
from syncthing_mcp.domain_hint import (
Pattern,
compute_domain_hint,
load_patterns_from_yaml,
)
from syncthing_mcp.registry import get_all_instances
# ---------------------------------------------------------------------------
# DD-338 A.2.dom.c — BladeConfigStore reader + Syncthing field projector
# ---------------------------------------------------------------------------
_BLADE_ID = "syncthing-blade-mcp"
def _state_root() -> str:
"""Resolve Stallari state root.
Honours ``STALLARI_STATE_ROOT`` env var (used in tests + non-standard
deployments); falls back to the macOS Application Support default per
Convention #27 / StallariPaths.
"""
override = os.environ.get("STALLARI_STATE_ROOT")
if override:
return override
return os.path.expanduser("~/Library/Application Support/Stallari")
def _sanitize_blade_id(blade_id: str) -> str:
"""Mirror the Swift writer's blade-id directory naming.
Lower-case + ``/`` ⇒ ``_`` — kept in lockstep with BladeConfigStore.swift
(Convention #23: reader and writer agree on the on-disk shape).
"""
return blade_id.lower().replace("/", "_")
def _load_blade_config(blade_id: str) -> list[Pattern]:
"""Read this blade's domain_hint patterns from the BladeConfigStore.
Convention #22 graceful degradation: missing / unreadable / malformed
config returns ``[]`` — the blade still runs, simply without per-record
``domain_hints`` emission.
Convention #23 reader-side compliance: resolves via state-root +
``blade-config/<sanitized-blade>/config.yaml`` in lockstep with the
Swift writer's path layout.
"""
config_path = os.path.join(
_state_root(),
"blade-config",
_sanitize_blade_id(blade_id),
"config.yaml",
)
try:
with open(config_path, encoding="utf-8") as f:
yaml_str = f.read()
except OSError:
return []
return load_patterns_from_yaml(yaml_str)
# Cached at module load; re-launch the blade to pick up config edits at v1.
_PATTERNS: list[Pattern] = _load_blade_config(_BLADE_ID)
def _syncthing_field_projector(record: dict[str, Any], field: str) -> Any:
"""Project a Syncthing record (folder OR device) onto a logical field name.
Polymorphic across the two record shapes this blade emits:
Folder record shape::
{"id": "...", "label": "...", "path": "...", "type": "sendreceive",
"devices": [...], "paused": false}
Device record shape::
{"deviceID": "ABCD-...", "name": "host", "addresses": [...],
"paused": false, "introducer": false}
Field resolution is shape-agnostic: try folder-side keys first, fall
through to device-side keys. Unknown field ⇒ ``None`` (no match).
"""
if not isinstance(record, dict):
return None
f = field
# Folder-shape fields
if f in {"id", "label", "path", "type"}:
v = record.get(f)
return v if v is not None else None
# Device-shape fields
if f == "deviceID":
return record.get("deviceID")
if f == "name":
return record.get("name")
if f == "addresses":
v = record.get("addresses")
return v if isinstance(v, list) else None
return None
def _record_id(record: dict[str, Any]) -> str | None:
"""Derive the stable per-record identifier.
Folders use ``id``; devices use ``deviceID``. The catalog enforces 1:1
record-id stability via ``deterministic_ordering=stable`` on the
catalog-mirror tools[] entries.
"""
if not isinstance(record, dict):
return None
rid = record.get("id")
if isinstance(rid, str):
return rid
rid = record.get("deviceID")
if isinstance(rid, str):
return rid
return None
def compute_domain_hints_for_records(
records: list[dict[str, Any]],
) -> dict[str, str]:
"""Apply ``_PATTERNS`` to each record; return ``{record_id: domain}`` map.
Records lacking a domain match are omitted. Empty pattern list ⇒ empty
dict ⇒ caller suppresses the ``domain_hints`` envelope key.
"""
if not _PATTERNS:
return {}
out: dict[str, str] = {}
for rec in records:
rid = _record_id(rec)
if rid is None:
continue
hint = compute_domain_hint(rec, _PATTERNS, _syncthing_field_projector)
if hint is not None:
out[rid] = hint
return out
@asynccontextmanager
async def app_lifespan(app):
import sys
+6 -1
View File
@@ -13,7 +13,7 @@ from syncthing_mcp.formatters import (
)
from syncthing_mcp.models import DeviceReadParams, ReadParams, _resolve_scope_folders
from syncthing_mcp.registry import get_instance, handle_error_global
from syncthing_mcp.server import mcp
from syncthing_mcp.server import compute_domain_hints_for_records, mcp
@mcp.tool(
@@ -72,6 +72,10 @@ async def syncthing_list_devices(params: ReadParams) -> str:
)
for dev in devices
]
# DD-338 A.2.dom.c — apply domain_hint patterns to raw device records
# (the formatter truncates deviceID in concise mode; use the source
# records so projector sees full deviceID + name + addresses).
domain_hints = compute_domain_hints_for_records(devices) or None
payload = fmt(result, concise=params.concise)
latency_ms = int((time.perf_counter() - start) * 1000)
return append_meta(
@@ -81,6 +85,7 @@ async def syncthing_list_devices(params: ReadParams) -> str:
filtered_by=filtered_by,
redactions=redactions,
latency_ms=latency_ms,
domain_hints=domain_hints,
)
except Exception as e:
return handle_error_global(e)
+25 -4
View File
@@ -1,15 +1,16 @@
"""Tools for instance management and listing folders (config-level)."""
import time
from typing import Any
from syncthing_mcp.formatters import fmt, format_folder
from syncthing_mcp.formatters import append_meta, fmt, format_folder
from syncthing_mcp.models import ReadParams
from syncthing_mcp.registry import (
get_all_instances,
get_instance,
handle_error_global,
)
from syncthing_mcp.server import mcp
from syncthing_mcp.server import compute_domain_hints_for_records, mcp
@mcp.tool(
@@ -63,7 +64,13 @@ async def syncthing_list_instances(params: ReadParams) -> str:
},
)
async def syncthing_list_folders(params: ReadParams) -> str:
"""All configured folders with labels, types, and device counts."""
"""All configured folders with labels, types, and device counts.
DD-338 A.2.dom.c — emits per-record ``domain_hints`` in the ``_meta``
envelope when the user has configured matching patterns via the
BladeConfigStore.
"""
start = time.perf_counter()
try:
client = get_instance(params.instance)
config = await client._get("/rest/config")
@@ -89,6 +96,20 @@ async def syncthing_list_folders(params: ReadParams) -> str:
"paused": f.get("paused", False),
"sharedWith": shared,
})
return fmt(result, concise=params.concise)
# Project domain hints from raw config records — they carry the
# full source-of-truth shape (`id`, `label`, `path`, `type`) the
# projector expects, even when ``concise`` collapses the output.
domain_hints = compute_domain_hints_for_records(folders) or None
payload = fmt(result, concise=params.concise)
latency_ms = int((time.perf_counter() - start) * 1000)
return append_meta(
payload,
matched_total=len(folders),
returned=len(result),
filtered_by=[],
redactions=[],
latency_ms=latency_ms,
domain_hints=domain_hints,
)
except Exception as e:
return handle_error_global(e)