tool.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. #!/usr/bin/env python3
  2. """Connection lifecycle tool for managed gateway accounts and local MCP servers.
  3. Disconnecting accounts remains a portal-only user decision.
  4. """
  5. from typing import Any, Callable, Dict, Optional
  6. from tools.connectors.catalog_tool import MANAGE_CATALOG_SCHEMA, manage_catalog
  7. from tools.connectors.gateway import config as gateway_config
  8. from tools.connectors.managed import run_managed_action
  9. from tools.connectors.mcp import run_mcp_operation
  10. from tools.connectors.targets import ALIAS_PATTERN, ALL_ACTIONS, MCP_ACTIONS, normalize_targets, validate_action
  11. from tools.registry import registry, tool_error
  12. def manage_connections(
  13. args: dict[str, Any],
  14. *,
  15. client_factory: Optional[Callable[[], Any]] = None,
  16. mcp_backend: Optional[Any] = None,
  17. session_id: Optional[str] = None,
  18. tool_call_id: Optional[str] = None,
  19. turn_id: Optional[str] = None,
  20. connection_callback: Optional[Callable[[dict[str, Any]], Optional[str]]] = None,
  21. connectors_available: Optional[Callable[[], bool]] = None,
  22. card_surface: bool = False,
  23. ) -> str:
  24. action = str(args.get("action") or "status").strip().lower()
  25. managed, mcp_targets, target_error = normalize_targets(args.get("connectors"))
  26. if target_error:
  27. return tool_error(target_error)
  28. action_error = validate_action(action, managed, mcp_targets)
  29. if action_error:
  30. return tool_error(action_error)
  31. if action in MCP_ACTIONS:
  32. return run_mcp_operation(
  33. mcp_targets, action, backend=mcp_backend,
  34. connection_callback=connection_callback, session_id=session_id, tool_call_id=tool_call_id,
  35. )
  36. return run_managed_action(
  37. action, managed, args,
  38. client_factory=client_factory, session_id=session_id, tool_call_id=tool_call_id, turn_id=turn_id,
  39. connection_callback=connection_callback, connectors_available=connectors_available,
  40. card_surface=card_surface,
  41. )
  42. MANAGE_CONNECTIONS_SCHEMA = {
  43. "name": "manage_connections",
  44. "description": (
  45. "Connect the user to apps. Two kinds: a hosted connector account (Gmail, Notion, ...) "
  46. "served through the tool gateway, and a local MCP server from the bundled catalog. "
  47. "Targets go in 'connectors': a bare slug or {\"name\": \"gmail\"} is a hosted connector "
  48. "account; {\"name\": \"linear\", \"mcp\": true} is a local MCP server. Many names exist on "
  49. "both sides, so the user's own words decide. Pass \"mcp\": true only when the user asks "
  50. "for an MCP server, a local server or an install, or when the name exists only as a "
  51. "catalog entry; otherwise the target is hosted. 'connect' and 'reconnect' are hosted "
  52. "actions; 'install', 'enable' and 'authorize' are MCP actions. A target the other side "
  53. "owns is refused with the call that does work. "
  54. "Hosted actions: 'display' (desktop only; elsewhere returns status) shows every connector and "
  55. "waits for Continue (300 s); put slugs to suggest in 'connectors'. Returns connected/newly_connected "
  56. "(+timed_out); the user saw the list, so do not repeat it. 'connect' is for an app the user names. "
  57. "'status' lists connectors and whether each is connected; 'connect' "
  58. "starts an authorization for the given connectors; 'reconnect' checks each one and "
  59. "repairs only what is not connected ('force': true restarts even a working one, for an "
  60. "account switch). A second account of one app is 'connect' with a new 'alias': pick a short "
  61. "lowercase name from the user's words (e.g. 'work'), and ask the user if unsure. 'status' lists "
  62. "each connector's accounts; 'rename' names or renames one. Pass SEVERAL slugs in one call. In the desktop app, the terminal UI and "
  63. "the interactive CLI the call shows the user a card and blocks until every app is "
  64. "connected, skipped, or the deadline passes; the result lists each target as connected / "
  65. "skipped / not_connected and never carries a link. Where no card exists (a one-shot run, "
  66. "a scheduled job, a messaging platform) the result carries a connect_url per app for the "
  67. "USER to open in a browser (never open it yourself); ask them to say when they are done, "
  68. "then use 'status'. "
  69. "When a hosted connector tool call returns CONNECTION_REQUIRED, use 'connect'. "
  70. "MCP actions (every target must carry \"mcp\": true): 'install' adds a catalog entry, "
  71. "'enable' re-enables a disabled configured server, 'authorize' runs its OAuth. "
  72. "They show the user an approval card and block until it settles. Never hand-edit "
  73. "mcp_servers config — always use this tool. After a skip or a timeout, do not re-ask on "
  74. "your own: continue without the app or ask in chat. A later request from the USER for that "
  75. "same app is not a re-ask — run it. A connected server's tools are named in the result and are "
  76. "callable at once through tool_describe/tool_call. Where no card exists an MCP target runs at once and the result says what "
  77. "happened, with a link for the user to open when one is needed. This tool can NOT "
  78. "disconnect, delete, or revoke an account — that is deliberately user-only. When asked, say so and direct the user to the "
  79. "Nous Portal (their org's Connectors page) or the desktop app."
  80. ),
  81. "parameters": {
  82. "type": "object",
  83. "properties": {
  84. "action": {
  85. "type": "string",
  86. "enum": list(ALL_ACTIONS),
  87. "description": (
  88. "Defaults to status. connect, reconnect and rename take hosted connector slugs only. "
  89. "install, enable and authorize take mcp:true targets only."
  90. ),
  91. },
  92. "connectors": {
  93. "type": "array",
  94. "items": {
  95. "anyOf": [
  96. {"type": "string"},
  97. {
  98. "type": "object",
  99. "properties": {
  100. "name": {"type": "string"},
  101. "mcp": {
  102. "type": "boolean",
  103. "description": (
  104. "true = a local MCP server from the catalog; absent or "
  105. "false = a hosted connector account."
  106. ),
  107. },
  108. "alias": {
  109. "type": "string",
  110. "description": (
  111. "Hosted only: the account's name. connect: a new name adds another "
  112. "account; reconnect: repairs that account; rename: its current name "
  113. "(or its label when unnamed). One aliased target per call."
  114. ),
  115. },
  116. "to": {
  117. "type": "string",
  118. "pattern": ALIAS_PATTERN,
  119. "description": "rename only: the new name.",
  120. },
  121. },
  122. "required": ["name"],
  123. "additionalProperties": False,
  124. },
  125. ]
  126. },
  127. "description": (
  128. "Targets. REQUIRED for every action but status and display "
  129. "(e.g. [\"gmail\", {\"name\": \"linear\", \"mcp\": true}]); optional filter for "
  130. "status. A bare slug is a hosted connector, so an MCP server needs the object "
  131. "form with \"mcp\": true."
  132. ),
  133. },
  134. "force": {
  135. "type": "boolean",
  136. "description": "reconnect only: restart the authorization even if the app is connected (account switch).",
  137. },
  138. },
  139. "required": [],
  140. },
  141. }
  142. registry.register(
  143. name="manage_connections",
  144. toolset="connections",
  145. schema=MANAGE_CONNECTIONS_SCHEMA,
  146. # The portal gate decides schema presence: an account the portal has not enabled for
  147. # connectors never sees the tool, so the model cannot call it and read the gateway's
  148. # 404 back to them. The handler runs the same gate so the RPC path (methods_connectors) and
  149. # a cached schema agree. Read as a module attribute so tests patch
  150. # ``gateway.config.connectors_available`` at one seam.
  151. handler=lambda args, **kw: manage_connections(
  152. args, session_id=kw.get("session_id"), tool_call_id=kw.get("tool_call_id"),
  153. connectors_available=gateway_config.connectors_available,
  154. ),
  155. check_fn=lambda: gateway_config.connectors_available(),
  156. emoji="🔗",
  157. )
  158. # Registry dispatch has no card callback, so it answers with the CLI pointer.
  159. registry.register(
  160. name="manage_catalog",
  161. toolset="catalog",
  162. schema=MANAGE_CATALOG_SCHEMA,
  163. handler=lambda args, **kw: manage_catalog(args, session_id=kw.get("session_id")),
  164. emoji="🧩",
  165. )