mcp_tool_scope.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. """Connection-ledger keys for tools.mcp_tool under a profile multiplexer.
  2. Every ledger in ``tools.mcp_tool`` (``_servers``, connecting/error/cooldown maps, circuit
  3. breaker, lazy configs, trust metadata) is keyed by a *connection key*: the bare server name
  4. outside a multiplexer (single-profile processes are unchanged, byte for byte), and
  5. ``(owner_scope, name)`` under one. Two profiles that both configure ``github`` with their own
  6. token are two connections; keying by name alone let the first profile's connection shadow the
  7. second's forever — its ``register_mcp_servers`` saw the name as "already connected", adopted
  8. nothing (different credentials) and left the profile silently tool-less (#106005, #91654).
  9. A profile may still *adopt* another profile's live connection when the route and credentials
  10. match (``mcp_tool_registration._same_server_route``); ``_server_tool_scopes[key]`` records every
  11. scope that has done so, and ``_resolve_server_key`` finds that shared connection for a caller
  12. whose own scope has none.
  13. """
  14. from __future__ import annotations
  15. from typing import Optional, Tuple, Union
  16. from tools.mcp_tool_common import _core
  17. ServerKey = str | tuple[str, str]
  18. def _server_key(name: str, scope: Optional[str] = None, *, current: bool = True) -> ServerKey:
  19. """Connection key for *name* owned by *scope* (the current registry scope when *current*).
  20. ``None`` scope (no multiplexer) keeps the bare name."""
  21. if scope is None and current:
  22. scope = _core._mcp_registry_scope()
  23. return name if scope is None else (scope, name)
  24. def _key_name(key: ServerKey) -> str:
  25. return key[1] if isinstance(key, tuple) else key
  26. def _key_scope(key: ServerKey) -> Optional[str]:
  27. """Owning registry scope encoded in *key* (None for a bare, unscoped key)."""
  28. return key[0] if isinstance(key, tuple) else None
  29. def _key_visible_in_scope(key: ServerKey, scope: Optional[str]) -> bool:
  30. """Whether the connection under *key* serves *scope*: owned by it or adopted into it.
  31. Caller holds ``_core._lock`` or tolerates a racy read (status surfaces)."""
  32. if scope is None:
  33. return True
  34. return _key_scope(key) == scope or scope in _core._server_tool_scopes.get(key, ())
  35. def _resolve_server_key(name: str, scope: Optional[str] = None, *, current: bool = True) -> ServerKey:
  36. """The connection key a call to *name* from *scope* must use: the scope's own connection
  37. (live, connecting or lazily registered) when it has one, else a shared connection it
  38. adopted, else its own (not yet existing) key so bookkeeping lands under this scope."""
  39. if scope is None and current:
  40. scope = _core._mcp_registry_scope()
  41. own = _server_key(name, scope, current=False)
  42. if scope is None or own in _core._servers or own in _core._lazy_server_configs:
  43. return own
  44. for key, scopes in _core._server_tool_scopes.items():
  45. if scope in scopes and _key_name(key) == name and key in _core._servers:
  46. return key
  47. return own
  48. # Ledgers keyed by connection key (``tools.mcp_tool``).
  49. _KEYED_LEDGERS = (
  50. "_servers", "_server_scope_keys", "_server_tool_scopes", "_server_connect_errors",
  51. "_lazy_server_configs", "_lazy_server_fingerprints", "_lazy_server_tool_names",
  52. "_server_connect_retry_after", "_server_connect_failures", "_server_error_counts",
  53. "_server_breaker_opened_at", "_server_errors_all_application", "_server_trust_levels",
  54. "_tool_read_only_hints", "_server_cost_policies")
  55. _KEYED_SETS = ("_server_connecting", "_parallel_safe_servers")
  56. def rekey_unscoped_connections(scope: str) -> None:
  57. """Move every bare-name connection under ``(scope, name)``. A single-profile process keys its
  58. connections by bare name; once it starts multiplexing, the launch profile's lookups resolve
  59. ``(launch scope, name)``, so without this its live servers read as disconnected until a restart."""
  60. from tools.registry import registry
  61. with _core._lock:
  62. for attr in _KEYED_LEDGERS:
  63. ledger = getattr(_core, attr)
  64. for key in [k for k in ledger if isinstance(k, str)]:
  65. ledger[(scope, key)] = ledger.pop(key)
  66. for attr in _KEYED_SETS:
  67. keys = getattr(_core, attr)
  68. bare = {k for k in keys if isinstance(k, str)}
  69. keys.difference_update(bare)
  70. keys.update((scope, k) for k in bare)
  71. # The owner and the tools follow the key: status, config pruning and /reload-mcp select by
  72. # owner == scope, and teardown deregisters from the owner's overlay, not the global map.
  73. tool_names = []
  74. for key in [k for k, owner in _core._server_scope_keys.items() if owner is None and _key_scope(k) == scope]:
  75. _core._server_scope_keys[key] = scope
  76. tool_names += getattr(_core._servers.get(key), "_registered_tool_names", None) or ()
  77. for key in [k for k in _core._lazy_server_tool_names if _key_scope(k) == scope]:
  78. tool_names += _core._lazy_server_tool_names[key]
  79. for key in set(_core._servers) | set(_core._lazy_server_tool_names):
  80. if _key_scope(key) == scope:
  81. _core._server_tool_scopes.setdefault(key, set()).add(scope)
  82. from tools.mcp_tool_costs import rekey_unscoped
  83. rekey_unscoped(scope) # chats' spend totals follow their server's policy key
  84. registry.move_to_scope(tool_names, scope)