targets.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. from __future__ import annotations
  2. import logging
  3. import re
  4. from dataclasses import dataclass
  5. from typing import Any, List, Optional, Set, Tuple
  6. logger = logging.getLogger(__name__)
  7. CONNECTOR_ACTIONS = ("display", "status", "connect", "reconnect", "rename")
  8. MCP_ACTIONS = ("install", "enable", "authorize")
  9. ALL_ACTIONS = CONNECTOR_ACTIONS + MCP_ACTIONS
  10. _TARGET_FIELDS = frozenset({"name", "mcp", "alias", "to"})
  11. ALIAS_PATTERN = r"^[a-z0-9][a-z0-9-]{0,31}$"
  12. _ALIAS_RE = re.compile(ALIAS_PATTERN)
  13. _ALIAS_FORMAT = "1-32 lowercase letters, digits or '-', starting with a letter or digit"
  14. @dataclass(frozen=True)
  15. class HostedTarget:
  16. """A hosted connector target. ``alias`` names one account of that connector; ``to`` is the
  17. new alias of a rename."""
  18. name: str
  19. alias: Optional[str] = None
  20. to: Optional[str] = None
  21. def _bad_alias(key: str, value: Optional[str]) -> Optional[str]:
  22. if value is None or _ALIAS_RE.fullmatch(value):
  23. return None
  24. return f"'{key}' {value!r} is not a valid account name: use {_ALIAS_FORMAT}."
  25. def normalize_targets(raw: Any) -> tuple[list[HostedTarget], list[str], Optional[str]]:
  26. if raw is None:
  27. return [], [], None
  28. if isinstance(raw, (str, dict)):
  29. raw = [raw]
  30. if not isinstance(raw, list):
  31. return [], [], "'connectors' must be a list of names or {name, mcp} objects."
  32. managed: list[HostedTarget] = []
  33. mcp: list[str] = []
  34. for item in raw:
  35. alias = to = None
  36. if isinstance(item, dict):
  37. unknown = sorted(set(item) - _TARGET_FIELDS)
  38. if unknown:
  39. return [], [], (
  40. f"unknown target field(s) {', '.join(unknown)}: a target is "
  41. "{\"name\": \"<slug>\"} or {\"name\": \"<server>\", \"mcp\": true}. Transport, "
  42. "URLs and credentials come from the catalog manifest, never from the call."
  43. )
  44. name = str(item.get("name") or "").strip().lower()
  45. is_mcp = bool(item.get("mcp", False))
  46. if is_mcp and ("alias" in item or "to" in item):
  47. return [], [], "'alias' and 'to' name hosted connector accounts; an MCP target takes neither."
  48. alias = str(item["alias"]).strip() if item.get("alias") is not None else None
  49. to = str(item["to"]).strip() if item.get("to") is not None else None
  50. else:
  51. name, is_mcp = str(item or "").strip().lower(), False
  52. if not name:
  53. return [], [], "every target needs a non-empty 'name'."
  54. if is_mcp:
  55. if name not in mcp:
  56. mcp.append(name)
  57. continue
  58. target = HostedTarget(name, alias, to)
  59. if all((t.name, t.alias) != (name, alias) for t in managed):
  60. managed.append(target)
  61. return managed, mcp, None
  62. def validate_action(action: str, managed: list[HostedTarget], mcp: list[str]) -> Optional[str]:
  63. if action not in ALL_ACTIONS:
  64. return (
  65. f"action must be one of {', '.join(ALL_ACTIONS)}. "
  66. f"{', '.join(MCP_ACTIONS)} apply to local MCP servers "
  67. "(targets {\"name\": ..., \"mcp\": true}); the rest apply to managed connectors. "
  68. "Disconnecting an account is done by the user in the Nous Portal dashboard, not "
  69. "through this tool."
  70. )
  71. if action in MCP_ACTIONS:
  72. if managed:
  73. return (
  74. f"'{action}' is an MCP action: every target must carry \"mcp\": true "
  75. f"(got managed connector(s) {', '.join(t.name for t in managed)}). Managed connectors use "
  76. "connect / reconnect / status."
  77. )
  78. if not mcp:
  79. return (
  80. f"'{action}' requires 'connectors': the MCP server name(s), e.g. "
  81. "[{\"name\": \"linear\", \"mcp\": true}]."
  82. )
  83. elif mcp:
  84. return (
  85. f"'{action}' is a managed-connector action; MCP targets ({', '.join(mcp)}) use "
  86. f"{', '.join(MCP_ACTIONS)}."
  87. )
  88. return _validate_accounts(action, managed)
  89. def _validate_accounts(action: str, managed: list[HostedTarget]) -> Optional[str]:
  90. if action != "rename" and any(t.to for t in managed):
  91. return "'to' is the new name of an account and applies to action rename only."
  92. if action == "display" and any(t.alias for t in managed):
  93. return "display takes connector slugs to suggest (e.g. [\"gmail\"]); accounts are named on connect."
  94. if action == "rename":
  95. if len(managed) != 1 or not managed[0].alias or not managed[0].to:
  96. return ("rename takes exactly one target {\"name\": \"<slug>\", \"alias\": \"<current name>\", "
  97. "\"to\": \"<new name>\"}. Use action status to list each connector's accounts.")
  98. # The current name may be the vendor's label of an unnamed account, so only the new one is checked.
  99. return _bad_alias("to", managed[0].to)
  100. if any(t.alias for t in managed) and len(managed) > 1:
  101. return "a call with an 'alias' takes that one target only; name other accounts in separate calls."
  102. if action == "reconnect":
  103. # Like rename, a repair may address an unnamed account by its label; the account read checks it.
  104. return None
  105. return next((e for t in managed if (e := _bad_alias("alias", t.alias))), None)
  106. def catalog_names() -> set[str]:
  107. try:
  108. from hermes_cli.mcp_catalog import list_catalog
  109. return {e.name for e in list_catalog()}
  110. except Exception as exc:
  111. logger.debug("MCP catalog for the routing check failed: %s", exc)
  112. return set()
  113. def hosted_names() -> Optional[set[str]]:
  114. try:
  115. from tools.connectors.gateway.client import ConnectorClient
  116. from tools.connectors.gateway.config import connectors_available
  117. if not connectors_available():
  118. return None
  119. return {str(item.get("connector", "")).lower()
  120. for item in ConnectorClient().list_connectors() if isinstance(item, dict)}
  121. except Exception as exc:
  122. logger.debug("connector list for the routing check failed: %s", exc)
  123. return None
  124. def misrouted_to_hosted_error(name: str) -> str:
  125. return (
  126. f"{name} is a local MCP server, not a hosted connector account. "
  127. f"Call manage_connections with action install and connectors "
  128. f"[{{\"name\": \"{name}\", \"mcp\": true}}]."
  129. )
  130. def misrouted_to_mcp_error(action: str, name: str) -> str:
  131. return (
  132. f"{name} is a hosted connector account, not a local MCP server, so '{action}' "
  133. f"does not apply. Call manage_connections with action connect and connectors [\"{name}\"]."
  134. )