Merge pull request #7 from Groupthink-dev/feat/dd-338-e-python-flip-mcp-helpers
DD-338 Phase E.python — depend on stallari-mcp-helpers (delete local helpers)
This commit is contained in:
13 files changed
+212
-348
No files matched your search
@@ -0,0 +1,41 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to `syncthing-blade-mcp` will be documented in this file.
|
||||
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
||||
|
||||
## [0.8.0] - 2026-05-24
|
||||
|
||||
### Changed
|
||||
|
||||
- **DD-338 Phase E.python — depend on `stallari-mcp-helpers>=0.1.0,<1.0.0`.**
|
||||
Local `meta_envelope` + `append_meta` helpers in `formatters.py` deleted;
|
||||
canonical implementations are now re-exported from the lib for backward
|
||||
call-site compatibility.
|
||||
- **`append_meta` signature is now `(body, meta_line)`** (lib semantics) where
|
||||
it previously accepted kwargs and built the envelope internally. The 11
|
||||
call-sites in `tools/folders.py`, `tools/instances.py`, `tools/system.py`,
|
||||
and `tools/devices.py` were refactored to the two-step pattern
|
||||
`append_meta(payload, meta_envelope(...))`.
|
||||
|
||||
### Wire-shape change (test fixtures updated)
|
||||
|
||||
- `_meta.filtered_by` continues to be sorted alphabetically inside the helper
|
||||
(unchanged — was already the behaviour of the local helper).
|
||||
- `_meta` field order now follows the canonical lib convention
|
||||
(`matched_total`, `returned`, `latency_ms`, `filtered_by`, `redactions`,
|
||||
`next_cursor`, `error_notes?`, `domain_hints?`). The prior local helper
|
||||
emitted `latency_ms` last.
|
||||
- `_meta.next_cursor` is now always present (defaults to `null`); the prior
|
||||
local helper omitted it entirely. The semantic OQ-4 invariant ("no cursor
|
||||
surfaced to callers in v1") is unchanged.
|
||||
- `_meta.redactions` continues to be emitted unconditionally as `[]` when
|
||||
empty (unchanged).
|
||||
- `_meta.error_notes` and `_meta.domain_hints` remain conditionally included
|
||||
only when non-empty (unchanged).
|
||||
|
||||
### Notes
|
||||
|
||||
- Pure substrate swap — no behavioural change to any tool. Pack-spec catalog
|
||||
declarations unchanged.
|
||||
|
||||
+2
-1
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "syncthing-blade-mcp"
|
||||
version = "0.7.0"
|
||||
version = "0.8.0"
|
||||
description = "MCP server for Syncthing — token-efficient replication management, multi-instance, safe disk-space reclamation."
|
||||
requires-python = ">=3.11"
|
||||
dependencies = [
|
||||
@@ -10,6 +10,7 @@ dependencies = [
|
||||
"uvicorn>=0.30.0",
|
||||
"starlette>=0.37.0",
|
||||
"pyyaml>=6.0",
|
||||
"stallari-mcp-helpers>=0.1.0,<1.0.0",
|
||||
]
|
||||
|
||||
[project.scripts]
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
"""Syncthing MCP Server — manage Syncthing instances via MCP tools."""
|
||||
|
||||
__version__ = "0.4.0"
|
||||
__version__ = "0.8.0"
|
||||
@@ -1,155 +0,0 @@
|
||||
"""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
|
||||
@@ -12,6 +12,8 @@ import json
|
||||
import random
|
||||
from typing import Any
|
||||
|
||||
from stallari_mcp_helpers import append_meta, meta_envelope
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Constants
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -33,69 +35,40 @@ def fmt(data: Any, *, concise: bool = True) -> str:
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# DD-338 Phase A.1 — Track 3 — _meta envelope (JSON tail block)
|
||||
# DD-338 Phase E.python — _meta envelope helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
#
|
||||
# Architect amendment 2026-05-21 — canonical wire shape is JSON tail block,
|
||||
# not pipe-delimited. Single line appended after \n\n. Assembler regex:
|
||||
# \n\n_meta: (\{.*\})$
|
||||
# Required fields: matched_total, returned, filtered_by, latency_ms.
|
||||
# Optional: redactions, next_cursor, error_notes.
|
||||
# filtered_by is sorted alphabetically for hash reproducibility.
|
||||
# Local `meta_envelope` + `append_meta` were retired in favour of the
|
||||
# canonical implementation in `stallari-mcp-helpers v0.1.0`. The lib API
|
||||
# differs slightly from this blade's prior local helper:
|
||||
#
|
||||
# - `meta_envelope(*, matched_total, returned, latency_ms, filtered_by=None,
|
||||
# redactions=None, next_cursor=None, error_notes=None, domain_hints=None)`
|
||||
# — `next_cursor` is a new optional kwarg the blade does not use.
|
||||
# - `append_meta(body, meta_line)` — takes a pre-built `_meta: {...}` line.
|
||||
# Callers must call `meta_envelope(...)` first then pass the result to
|
||||
# `append_meta`. Previously this blade's `append_meta` built the envelope
|
||||
# internally.
|
||||
#
|
||||
# Wire-shape change (test fixtures updated for byte-equal pins):
|
||||
# - Field order in the rendered JSON now follows lib convention
|
||||
# (matched_total, returned, latency_ms, filtered_by, redactions,
|
||||
# next_cursor, error_notes?, domain_hints?). The prior local helper
|
||||
# emitted latency_ms last.
|
||||
# - `next_cursor: null` is now always present.
|
||||
# - `redactions` and `filtered_by` continue to be emitted unconditionally
|
||||
# (as `[]` when empty); `error_notes` and `domain_hints` are omitted
|
||||
# when empty.
|
||||
#
|
||||
# The lib re-exports preserve the same call names (`meta_envelope`,
|
||||
# `append_meta`) so blade tool modules continue importing them from
|
||||
# `syncthing_mcp.formatters`.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def meta_envelope(
|
||||
*,
|
||||
matched_total: int,
|
||||
returned: int,
|
||||
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: 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=(",", ":"))
|
||||
|
||||
|
||||
def append_meta(
|
||||
payload: str,
|
||||
*,
|
||||
matched_total: int,
|
||||
returned: int,
|
||||
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(
|
||||
matched_total=matched_total,
|
||||
returned=returned,
|
||||
filtered_by=filtered_by,
|
||||
redactions=redactions,
|
||||
latency_ms=latency_ms,
|
||||
domain_hints=domain_hints,
|
||||
)
|
||||
# Re-export `meta_envelope` + `append_meta` from the lib so existing imports
|
||||
# from `syncthing_mcp.formatters` continue to resolve.
|
||||
_ = (append_meta, meta_envelope) # explicit re-export marker; suppresses lint
|
||||
|
||||
|
||||
def short_id(device_id: str) -> str:
|
||||
|
||||
+17
-36
@@ -8,7 +8,7 @@ from mcp.server.fastmcp import FastMCP
|
||||
from starlette.requests import Request
|
||||
from starlette.responses import JSONResponse
|
||||
|
||||
from syncthing_mcp.domain_hint import (
|
||||
from stallari_mcp_helpers import (
|
||||
Pattern,
|
||||
compute_domain_hint,
|
||||
load_patterns_from_yaml,
|
||||
@@ -74,40 +74,14 @@ def _load_blade_config(blade_id: str) -> list[Pattern]:
|
||||
_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
|
||||
# DD-338 Phase E.python — the per-blade `_syncthing_field_projector` was
|
||||
# retired here. The canonical `compute_domain_hint` in
|
||||
# `stallari-mcp-helpers v0.1.0` uses built-in dot-path field resolution,
|
||||
# which behaves identically to the prior projector for the flat record
|
||||
# shapes this blade emits (folders: `id` / `label` / `path` / `type`;
|
||||
# devices: `deviceID` / `name` / `addresses`). Should a future record
|
||||
# shape introduce nested fields requiring custom projection, re-introduce
|
||||
# a lib-side projector hook or override the relevant call-site.
|
||||
|
||||
|
||||
def _record_id(record: dict[str, Any]) -> str | None:
|
||||
@@ -143,7 +117,14 @@ def compute_domain_hints_for_records(
|
||||
rid = _record_id(rec)
|
||||
if rid is None:
|
||||
continue
|
||||
hint = compute_domain_hint(rec, _PATTERNS, _syncthing_field_projector)
|
||||
# DD-338 Phase E.python — canonical lib's `compute_domain_hint` uses
|
||||
# built-in dot-path resolution; the local `_syncthing_field_projector`
|
||||
# below is retained for the test suite only. For Syncthing record
|
||||
# shapes (folders + devices) the dot-path resolution behaves identically
|
||||
# to the prior projector — both navigate `record.get(field)` for the
|
||||
# flat keys actually used in patterns (`id`, `label`, `path`, `type`,
|
||||
# `deviceID`, `name`, `addresses`).
|
||||
hint = compute_domain_hint(rec, _PATTERNS)
|
||||
if hint is not None:
|
||||
out[rid] = hint
|
||||
return out
|
||||
|
||||
@@ -9,6 +9,7 @@ from syncthing_mcp.formatters import (
|
||||
format_bytes,
|
||||
format_connection,
|
||||
format_device,
|
||||
meta_envelope,
|
||||
truncate,
|
||||
)
|
||||
from syncthing_mcp.models import DeviceReadParams, ReadParams, _resolve_scope_folders
|
||||
@@ -80,12 +81,14 @@ async def syncthing_list_devices(params: ReadParams) -> str:
|
||||
latency_ms = int((time.perf_counter() - start) * 1000)
|
||||
return append_meta(
|
||||
payload,
|
||||
matched_total=matched_total,
|
||||
returned=len(result),
|
||||
filtered_by=filtered_by,
|
||||
redactions=redactions,
|
||||
latency_ms=latency_ms,
|
||||
domain_hints=domain_hints,
|
||||
meta_envelope(
|
||||
matched_total=matched_total,
|
||||
returned=len(result),
|
||||
filtered_by=filtered_by,
|
||||
redactions=redactions,
|
||||
latency_ms=latency_ms,
|
||||
domain_hints=domain_hints,
|
||||
),
|
||||
)
|
||||
except Exception as e:
|
||||
return handle_error_global(e)
|
||||
|
||||
@@ -10,6 +10,7 @@ from syncthing_mcp.formatters import (
|
||||
format_completion,
|
||||
format_folder_status,
|
||||
format_replication_entry,
|
||||
meta_envelope,
|
||||
truncate,
|
||||
)
|
||||
from syncthing_mcp.models import (
|
||||
@@ -65,11 +66,13 @@ async def syncthing_folder_status(params: FolderReadParams) -> str:
|
||||
latency_ms = int((time.perf_counter() - start) * 1000)
|
||||
return append_meta(
|
||||
error_payload,
|
||||
matched_total=0,
|
||||
returned=0,
|
||||
filtered_by=filtered_by,
|
||||
redactions=[*redactions, "folder_outside_scope"],
|
||||
latency_ms=latency_ms,
|
||||
meta_envelope(
|
||||
matched_total=0,
|
||||
returned=0,
|
||||
filtered_by=filtered_by,
|
||||
redactions=[*redactions, 'folder_outside_scope'],
|
||||
latency_ms=latency_ms,
|
||||
),
|
||||
)
|
||||
|
||||
filtered_by.append(f"folder={params.folder_id}")
|
||||
@@ -90,11 +93,13 @@ async def syncthing_folder_status(params: FolderReadParams) -> str:
|
||||
latency_ms = int((time.perf_counter() - start) * 1000)
|
||||
return append_meta(
|
||||
payload,
|
||||
matched_total=1,
|
||||
returned=1,
|
||||
filtered_by=filtered_by,
|
||||
redactions=redactions,
|
||||
latency_ms=latency_ms,
|
||||
meta_envelope(
|
||||
matched_total=1,
|
||||
returned=1,
|
||||
filtered_by=filtered_by,
|
||||
redactions=redactions,
|
||||
latency_ms=latency_ms,
|
||||
),
|
||||
)
|
||||
except Exception as e:
|
||||
return handle_error_global(e)
|
||||
@@ -282,11 +287,13 @@ async def syncthing_replication_report(params: ReadParams) -> str:
|
||||
latency_ms = int((time.perf_counter() - start) * 1000)
|
||||
return append_meta(
|
||||
payload,
|
||||
matched_total=matched_total,
|
||||
returned=len(report),
|
||||
filtered_by=filtered_by,
|
||||
redactions=redactions,
|
||||
latency_ms=latency_ms,
|
||||
meta_envelope(
|
||||
matched_total=matched_total,
|
||||
returned=len(report),
|
||||
filtered_by=filtered_by,
|
||||
redactions=redactions,
|
||||
latency_ms=latency_ms,
|
||||
),
|
||||
)
|
||||
except Exception as e:
|
||||
return handle_error_global(e)
|
||||
@@ -411,11 +418,13 @@ async def syncthing_folder_errors(params: FolderReadParams) -> str:
|
||||
latency_ms = int((time.perf_counter() - start) * 1000)
|
||||
return append_meta(
|
||||
error_payload,
|
||||
matched_total=0,
|
||||
returned=0,
|
||||
filtered_by=filtered_by,
|
||||
redactions=[*redactions, "folder_outside_scope"],
|
||||
latency_ms=latency_ms,
|
||||
meta_envelope(
|
||||
matched_total=0,
|
||||
returned=0,
|
||||
filtered_by=filtered_by,
|
||||
redactions=[*redactions, 'folder_outside_scope'],
|
||||
latency_ms=latency_ms,
|
||||
),
|
||||
)
|
||||
|
||||
filtered_by.append(f"folder={params.folder_id}")
|
||||
@@ -434,11 +443,13 @@ async def syncthing_folder_errors(params: FolderReadParams) -> str:
|
||||
latency_ms = int((time.perf_counter() - start) * 1000)
|
||||
return append_meta(
|
||||
payload,
|
||||
matched_total=len(error_list),
|
||||
returned=len(error_list),
|
||||
filtered_by=filtered_by,
|
||||
redactions=redactions,
|
||||
latency_ms=latency_ms,
|
||||
meta_envelope(
|
||||
matched_total=len(error_list),
|
||||
returned=len(error_list),
|
||||
filtered_by=filtered_by,
|
||||
redactions=redactions,
|
||||
latency_ms=latency_ms,
|
||||
),
|
||||
)
|
||||
except Exception as e:
|
||||
return handle_error_global(e)
|
||||
@@ -485,10 +496,12 @@ async def syncthing_browse_folder(params: BrowseFolderInput) -> str:
|
||||
latency_ms = int((time.perf_counter() - start) * 1000)
|
||||
return append_meta(
|
||||
payload,
|
||||
matched_total=entries_count,
|
||||
returned=entries_count,
|
||||
filtered_by=filtered_by,
|
||||
latency_ms=latency_ms,
|
||||
meta_envelope(
|
||||
matched_total=entries_count,
|
||||
returned=entries_count,
|
||||
filtered_by=filtered_by,
|
||||
latency_ms=latency_ms,
|
||||
),
|
||||
)
|
||||
except Exception as e:
|
||||
return handle_error_global(e)
|
||||
@@ -590,10 +603,12 @@ async def syncthing_folder_need(params: FolderNeedInput) -> str:
|
||||
latency_ms = int((time.perf_counter() - start) * 1000)
|
||||
return append_meta(
|
||||
payload,
|
||||
matched_total=returned_count,
|
||||
returned=returned_count,
|
||||
filtered_by=filtered_by,
|
||||
latency_ms=latency_ms,
|
||||
meta_envelope(
|
||||
matched_total=returned_count,
|
||||
returned=returned_count,
|
||||
filtered_by=filtered_by,
|
||||
latency_ms=latency_ms,
|
||||
),
|
||||
)
|
||||
except Exception as e:
|
||||
return handle_error_global(e)
|
||||
@@ -653,10 +668,12 @@ async def syncthing_remote_need(params: RemoteNeedInput) -> str:
|
||||
latency_ms = int((time.perf_counter() - start) * 1000)
|
||||
return append_meta(
|
||||
payload,
|
||||
matched_total=returned_count,
|
||||
returned=returned_count,
|
||||
filtered_by=filtered_by,
|
||||
latency_ms=latency_ms,
|
||||
meta_envelope(
|
||||
matched_total=returned_count,
|
||||
returned=returned_count,
|
||||
filtered_by=filtered_by,
|
||||
latency_ms=latency_ms,
|
||||
),
|
||||
)
|
||||
except Exception as e:
|
||||
return handle_error_global(e)
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
from syncthing_mcp.formatters import append_meta, fmt, format_folder
|
||||
from syncthing_mcp.formatters import append_meta, fmt, format_folder, meta_envelope
|
||||
from syncthing_mcp.models import ReadParams, _resolve_scope_folders
|
||||
from syncthing_mcp.registry import (
|
||||
get_all_instances,
|
||||
@@ -117,12 +117,14 @@ async def syncthing_list_folders(params: ReadParams) -> str:
|
||||
latency_ms = int((time.perf_counter() - start) * 1000)
|
||||
return append_meta(
|
||||
payload,
|
||||
matched_total=matched_total,
|
||||
returned=len(result),
|
||||
filtered_by=filtered_by,
|
||||
redactions=redactions,
|
||||
latency_ms=latency_ms,
|
||||
domain_hints=domain_hints,
|
||||
meta_envelope(
|
||||
matched_total=matched_total,
|
||||
returned=len(result),
|
||||
filtered_by=filtered_by,
|
||||
redactions=redactions,
|
||||
latency_ms=latency_ms,
|
||||
domain_hints=domain_hints,
|
||||
),
|
||||
)
|
||||
except Exception as e:
|
||||
return handle_error_global(e)
|
||||
@@ -5,7 +5,7 @@ from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from syncthing_mcp.formatters import append_meta, fmt, format_bytes, truncate
|
||||
from syncthing_mcp.formatters import append_meta, fmt, format_bytes, meta_envelope, truncate
|
||||
from syncthing_mcp.models import ReadParams, WriteParams, _resolve_scope_folders
|
||||
from syncthing_mcp.registry import get_instance, handle_error_global
|
||||
from syncthing_mcp.server import mcp
|
||||
@@ -192,11 +192,13 @@ async def syncthing_recent_changes(params: ReadParams) -> str:
|
||||
latency_ms = int((time.perf_counter() - start) * 1000)
|
||||
return append_meta(
|
||||
payload,
|
||||
matched_total=matched_total,
|
||||
returned=len(events),
|
||||
filtered_by=filtered_by,
|
||||
redactions=redactions,
|
||||
latency_ms=latency_ms,
|
||||
meta_envelope(
|
||||
matched_total=matched_total,
|
||||
returned=len(events),
|
||||
filtered_by=filtered_by,
|
||||
redactions=redactions,
|
||||
latency_ms=latency_ms,
|
||||
),
|
||||
)
|
||||
except Exception as e:
|
||||
return handle_error_global(e)
|
||||
|
||||
+18
-37
@@ -1,42 +1,23 @@
|
||||
"""DD-338 A.2.dom.c — domain_hint pattern engine tests.
|
||||
"""DD-338 A.2.dom.c — domain_hint pattern engine smoke-tests.
|
||||
|
||||
Tests the pure engine (Pattern, compute_domain_hint, load_patterns_from_yaml)
|
||||
plus a local copy of the Syncthing field projector so the test file doesn't
|
||||
trigger FastMCP server boot via ``syncthing_mcp.server`` import.
|
||||
DD-338 Phase E.python — the pattern engine moved from the local
|
||||
``syncthing_mcp.domain_hint`` module to the canonical
|
||||
``stallari_mcp_helpers`` package. These tests now exercise the lib's
|
||||
public surface and serve as a lightweight blade-side smoke-test
|
||||
confirming the lib resolves the record shapes this blade emits
|
||||
(folders + devices) correctly. The lib's own test suite is the
|
||||
authoritative coverage layer.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from syncthing_mcp.domain_hint import (
|
||||
from stallari_mcp_helpers import (
|
||||
Pattern,
|
||||
compute_domain_hint,
|
||||
load_patterns_from_yaml,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Local copy of _syncthing_field_projector — mirrors server.py to avoid
|
||||
# importing the FastMCP server module (which spins up registry on import).
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _projector(record: dict[str, Any], field: str) -> Any:
|
||||
if not isinstance(record, dict):
|
||||
return None
|
||||
if field in {"id", "label", "path", "type"}:
|
||||
return record.get(field)
|
||||
if field == "deviceID":
|
||||
return record.get("deviceID")
|
||||
if field == "name":
|
||||
return record.get("name")
|
||||
if field == "addresses":
|
||||
v = record.get("addresses")
|
||||
return v if isinstance(v, list) else None
|
||||
return None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# compute_domain_hint
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -45,7 +26,7 @@ def _projector(record: dict[str, Any], field: str) -> Any:
|
||||
def test_empty_patterns_returns_none() -> None:
|
||||
"""No patterns ⇒ no domain hint regardless of record shape."""
|
||||
record = {"id": "test", "label": "Test", "path": "/Family/photos"}
|
||||
assert compute_domain_hint(record, [], _projector) is None
|
||||
assert compute_domain_hint(record, []) is None
|
||||
|
||||
|
||||
def test_single_pattern_match_folder() -> None:
|
||||
@@ -57,7 +38,7 @@ def test_single_pattern_match_folder() -> None:
|
||||
"type": "sendreceive",
|
||||
}
|
||||
patterns = [Pattern(field="path", op="contains", value="/Family/", domain="family")]
|
||||
assert compute_domain_hint(record, patterns, _projector) == "family"
|
||||
assert compute_domain_hint(record, patterns) == "family"
|
||||
|
||||
|
||||
def test_first_match_wins() -> None:
|
||||
@@ -72,21 +53,21 @@ def test_first_match_wins() -> None:
|
||||
Pattern(field="path", op="contains", value="/work/", domain="work"),
|
||||
Pattern(field="path", op="contains", value="/Family/", domain="family"),
|
||||
]
|
||||
assert compute_domain_hint(record, patterns, _projector) == "work"
|
||||
assert compute_domain_hint(record, patterns) == "work"
|
||||
|
||||
|
||||
def test_glob_wildcard_on_label() -> None:
|
||||
"""fnmatch glob op handles wildcard label matches."""
|
||||
record = {"id": "f1", "label": "Work Notes", "path": "/x"}
|
||||
patterns = [Pattern(field="label", op="glob", value="Work*", domain="work")]
|
||||
assert compute_domain_hint(record, patterns, _projector) == "work"
|
||||
assert compute_domain_hint(record, patterns) == "work"
|
||||
|
||||
|
||||
def test_projector_returns_none_for_unknown_field() -> None:
|
||||
"""Unknown projector field ⇒ no match, no crash."""
|
||||
def test_unknown_field_returns_none() -> None:
|
||||
"""Unknown field path ⇒ no match, no crash."""
|
||||
record = {"id": "f1", "label": "L", "path": "/x"}
|
||||
patterns = [Pattern(field="nonsense", op="equals", value="x", domain="d")]
|
||||
assert compute_domain_hint(record, patterns, _projector) is None
|
||||
assert compute_domain_hint(record, patterns) is None
|
||||
|
||||
|
||||
def test_device_record_addresses_list_match() -> None:
|
||||
@@ -97,14 +78,14 @@ def test_device_record_addresses_list_match() -> None:
|
||||
"addresses": ["dynamic", "tcp://10.0.0.5:22000"],
|
||||
}
|
||||
patterns = [Pattern(field="addresses", op="contains", value="10.0.0.5", domain="ops")]
|
||||
assert compute_domain_hint(record, patterns, _projector) == "ops"
|
||||
assert compute_domain_hint(record, patterns) == "ops"
|
||||
|
||||
|
||||
def test_device_record_equals_deviceid() -> None:
|
||||
"""Exact deviceID match emits the configured domain."""
|
||||
record = {"deviceID": "ABCDEFG-XYZ", "name": "h"}
|
||||
patterns = [Pattern(field="deviceID", op="equals", value="ABCDEFG-XYZ", domain="ops")]
|
||||
assert compute_domain_hint(record, patterns, _projector) == "ops"
|
||||
assert compute_domain_hint(record, patterns) == "ops"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -491,8 +491,10 @@ class TestFolderNeed:
|
||||
assert isinstance(meta["returned"], int)
|
||||
assert isinstance(meta["latency_ms"], int)
|
||||
assert meta["returned"] == 3
|
||||
# next_cursor must NOT be present per OQ-4 (v1)
|
||||
assert "next_cursor" not in meta
|
||||
# DD-338 Phase E.python — canonical lib always emits `next_cursor`
|
||||
# (as `null` when caller passes None / omits the kwarg); semantic
|
||||
# OQ-4 invariant unchanged (no cursor surfaced to callers in v1).
|
||||
assert meta["next_cursor"] is None
|
||||
|
||||
# DD-338 Phase C Wave 2 — filtered_by content
|
||||
async def test_filtered_by_contains_pagination(self, mock_api):
|
||||
@@ -549,7 +551,9 @@ class TestRemoteNeed:
|
||||
assert isinstance(meta["returned"], int)
|
||||
assert isinstance(meta["latency_ms"], int)
|
||||
assert meta["returned"] == 3
|
||||
assert "next_cursor" not in meta
|
||||
# DD-338 Phase E.python — canonical lib always emits `next_cursor`
|
||||
# (as `null` when caller passes None / omits the kwarg).
|
||||
assert meta["next_cursor"] is None
|
||||
|
||||
# DD-338 Phase C Wave 2 — filtered_by content
|
||||
async def test_filtered_by_contains_device_and_pagination(self, mock_api):
|
||||
|
||||
@@ -810,6 +810,18 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/96/7f/832f015020844a8b8f7a9cbc103dd76ba8e3875004c41e08440ea3a2b41a/sse_starlette-3.2.0-py3-none-any.whl", hash = "sha256:5876954bd51920fc2cd51baee47a080eb88a37b5b784e615abb0b283f801cdbf", size = 12763, upload-time = "2026-01-17T13:11:03.775Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "stallari-mcp-helpers"
|
||||
version = "0.1.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "pyyaml" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/f4/c6/0fc259a84c5d7bde39c0bcfdaf17198a37a02125f5b76465796b375ca8db/stallari_mcp_helpers-0.1.0.tar.gz", hash = "sha256:1d6f587a38279c9eaef1975cd9ad1984e98e9b820ae8ac75c9321fd85dd15c89", size = 53315, upload-time = "2026-05-23T23:17:14.605Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/4f/e3/0e5bbbec5958b51a698f971cef7b8df7f18651579f01cd89b9dcbc96412f/stallari_mcp_helpers-0.1.0-py3-none-any.whl", hash = "sha256:a82d3615c338db4498b19c784599a3c5ff966046b25823f9b9fbdf9a802c66b9", size = 9581, upload-time = "2026-05-23T23:17:13.294Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "starlette"
|
||||
version = "0.52.1"
|
||||
@@ -825,13 +837,14 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "syncthing-blade-mcp"
|
||||
version = "0.7.0"
|
||||
version = "0.8.0"
|
||||
source = { editable = "." }
|
||||
dependencies = [
|
||||
{ name = "httpx" },
|
||||
{ name = "mcp", extra = ["cli"] },
|
||||
{ name = "pydantic" },
|
||||
{ name = "pyyaml" },
|
||||
{ name = "stallari-mcp-helpers" },
|
||||
{ name = "starlette" },
|
||||
{ name = "uvicorn" },
|
||||
]
|
||||
@@ -849,6 +862,7 @@ requires-dist = [
|
||||
{ name = "mcp", extras = ["cli"], specifier = ">=1.0.0" },
|
||||
{ name = "pydantic", specifier = ">=2.0.0" },
|
||||
{ name = "pyyaml", specifier = ">=6.0" },
|
||||
{ name = "stallari-mcp-helpers", specifier = ">=0.1.0,<1.0.0" },
|
||||
{ name = "starlette", specifier = ">=0.37.0" },
|
||||
{ name = "uvicorn", specifier = ">=0.30.0" },
|
||||
]
|
||||
|
||||
Reference in new issue
Block a user