Enterprise agent platform for building, deploying, and operating AI teammates.
feat(v1): read and replace an agent's connectors with a personal key (#3778)
Alex Liub4c171a90ae5
diff --git a/src/xagent/web/api/v1/agents.py b/src/xagent/web/api/v1/agents.pyindex 530b88eba..0ab851882 100644--- a/src/xagent/web/api/v1/agents.py+++ b/src/xagent/web/api/v1/agents.py@@ -4,6 +4,8 @@ from fastapi import APIRouter, Depends, Path, Requestfrom ...schemas.v1 import (RuntimeKeyResponse,+ V1AgentConnectorsResponse,+ V1AgentConnectorsUpdateRequest,V1AgentCreateRequest,V1AgentCreateResponse,V1AgentResponse,@@ -14,11 +16,15 @@ from ...schemas.v1 import (V1AgentTemplateCreateRequest,)from ...services.agent_management import (+ AgentConnectorsNotSharedError,+ AgentConnectorsSnapshot,AgentCreateSpec,AgentManagementRuntime,AgentResponseSnapshot,AgentSummarySnapshot,+ AgentToolsUnconfiguredError,DuplicateAgentNameError,+ InvalidAgentConnectorsError,InvalidAgentModelConfigError,InvalidAgentSkillNamesError,InvalidKnowledgeBaseError,@@ -262,3 +268,67 @@ async def set_agent_skills(skills=list(result.skills),unresolved_for_caller=list(result.unresolved_for_caller),)+++def _connectors_response(+ agent_id: int, selection: AgentConnectorsSnapshot+) -> V1AgentConnectorsResponse:+ return V1AgentConnectorsResponse(+ agent_id=agent_id,+ connectors=list(selection.connectors),+ all_connectors=selection.all_connectors,+ unresolved=list(selection.unresolved),+ )++[email protected]("/{agent_id}/connectors", response_model=V1AgentConnectorsResponse)+async def get_agent_connectors(+ # ``agents.id`` is a 32-bit integer column.+ agent_id: int = Path(gt=0, le=2**31 - 1),+ authed: tuple[UserPrincipalSnapshot, PersonalApiKeySnapshot] = Depends(+ get_user_from_personal_key+ ),+) -> V1AgentConnectorsResponse:+ """Read the connectors of an agent the key holder can see."""+ user, _key = authed+ selection = await AgentManagementRuntime().get_agent_connectors(+ user_id=int(user.id), agent_id=agent_id+ )+ if selection is None:+ raise V1ApiError(V1ErrorCode.AGENT_NOT_FOUND, 404)+ return _connectors_response(agent_id, selection)++[email protected]("/{agent_id}/connectors", response_model=V1AgentConnectorsResponse)+async def set_agent_connectors(+ request: V1AgentConnectorsUpdateRequest,+ # ``agents.id`` is a 32-bit integer column.+ agent_id: int = Path(gt=0, le=2**31 - 1),+ authed: tuple[UserPrincipalSnapshot, PersonalApiKeySnapshot] = Depends(+ get_user_from_personal_key+ ),+) -> V1AgentConnectorsResponse:+ """Replace the connectors of an agent the key holder can see."""+ user, key = authed+ try:+ selection = await AgentManagementRuntime().set_agent_connectors(+ user_id=int(user.id),+ key_prefix=key.key_prefix,+ agent_id=agent_id,+ connectors=request.connectors,+ all_connectors=request.all_connectors,+ )+ except AgentToolsUnconfiguredError:+ raise V1ApiError(V1ErrorCode.AGENT_TOOLS_UNCONFIGURED, 409)+ except InvalidAgentConnectorsError as e:+ raise V1ApiError(V1ErrorCode.INVALID_INPUT, 400, str(e))+ except AgentConnectorsNotSharedError as e:+ raise V1ApiError(+ V1ErrorCode.CONNECTOR_NOT_SHARED,+ 400,+ str(e),+ details={"connectors": e.connectors},+ )+ if selection is None:+ raise V1ApiError(V1ErrorCode.AGENT_NOT_FOUND, 404)+ return _connectors_response(agent_id, selection)diff --git a/src/xagent/web/api/v1/errors.py b/src/xagent/web/api/v1/errors.pyindex 24d20be1f..8789f3db2 100644--- a/src/xagent/web/api/v1/errors.py+++ b/src/xagent/web/api/v1/errors.py@@ -147,6 +147,15 @@ class V1ErrorCode(str, Enum):CONNECTOR_NOT_FOUND = "connector_not_found"+ # A team agent would select connectors its team cannot use. 400.+ # ``details.connectors`` lists each one as ``{"name", "reason"}`` with+ # ``reason`` one of ``not_shared``, ``disabled`` or ``unresolved``.+ CONNECTOR_NOT_SHARED = "connector_not_shared"++ # The agent has never had its tools chosen and uses the default tool+ # set, so there is no selection to read connectors from or replace. 409.+ AGENT_TOOLS_UNCONFIGURED = "agent_tools_unconfigured"+# The connector's transport is not one the API can create, change or list# tools for (only ``streamable_http`` and ``sse``). 400.TRANSPORT_NOT_SUPPORTED = "transport_not_supported"@@ -286,6 +295,12 @@ _DEFAULT_MESSAGES: dict[V1ErrorCode, str] = {V1ErrorCode.INTERNAL_ERROR: "Internal server error.",V1ErrorCode.AUTO_MODEL_UNAVAILABLE: CLIENT_SAFE_AUTO_MODEL_UNAVAILABLE,V1ErrorCode.CONNECTOR_NOT_FOUND: "Connector not found or not accessible.",+ V1ErrorCode.CONNECTOR_NOT_SHARED: (+ "The agent would select connectors its team cannot use."+ ),+ V1ErrorCode.AGENT_TOOLS_UNCONFIGURED: (+ "This agent uses the default tool set; choose its tools in the web app first."+ ),V1ErrorCode.TRANSPORT_NOT_SUPPORTED: ("Only the streamable_http and sse transports are supported through the API."),diff --git a/src/xagent/web/schemas/v1.py b/src/xagent/web/schemas/v1.pyindex ac81d2d2d..fb7d0f902 100644--- a/src/xagent/web/schemas/v1.py+++ b/src/xagent/web/schemas/v1.py@@ -453,6 +453,101 @@ class V1AgentSkillsUpdateResponse(V1AgentSkillsResponse):)+class V1AgentConnectorsResponse(BaseModel):+ """Response of ``GET`` and ``PUT /v1/agents/{agent_id}/connectors``."""++ agent_id: int+ connectors: list[str] = Field(+ ...,+ description=(+ "The connector names the agent selects, as stored: in stored "+ "order, a repeated name repeated. An agent that uses the default "+ "tool set selects none."+ ),+ )+ all_connectors: bool = Field(+ ...,+ description=(+ "True when the agent uses the default tool set, or its tool list "+ "has the category that selects every MCP connector."+ ),+ )+ unresolved: list[str] = Field(+ ...,+ description=(+ "Names in ``connectors`` that are not among the connectors the key "+ "holder can see through this API. This is computed for the key "+ "holder and can differ from the set a task loads when it runs."+ ),+ )+++class V1AgentConnectorsUpdateRequest(BaseModel):+ """Body for ``PUT /v1/agents/{agent_id}/connectors``.++ The agent's connector selection is replaced as a whole, so read it with+ ``GET`` first and send it back with your change. Entries of the agent's+ tool list that do not select a connector keep their relative order, and+ the connector entries follow them in the order given here. Sending back+ exactly what ``GET`` returned changes nothing and writes nothing.++ Only names this request adds are checked: each must be a connector the key+ holder can see. A name already on the agent is kept even when the key+ holder cannot see it, and ``unresolved`` in the response lists it. A+ connector the key holder has disabled for themselves can be added to a+ personal agent; it is stored and listed as resolved, and tasks load it+ only once it is enabled again. A connector the key holder sees only+ because their team shares it is also accepted and listed as resolved,+ but a task takes team connectors from the team that owns the agent, so a+ task of a personal agent runs without it.++ For an agent that belongs to a team, the new list, with the category that+ selects every connector when ``all_connectors`` is true, is checked by the+ team connector validator the deployment installs. A list it refuses fails+ with ``connector_not_shared``; whether ``all_connectors=true`` is accepted+ is also its decision. With no validator installed, this check refuses+ nothing. An agent that uses the default tool set is refused with+ ``agent_tools_unconfigured``.++ New tasks use the new selection at once. An existing task keeps using the+ previous one while its cached agent runtime is alive; each server process+ has its own cache, and how long a runtime stays cached depends on the+ task's state. If the agent is the manager or an enabled worker of a+ workforce and its tool list now differs, other than in order, from the+ list it had when an ongoing workforce conversation started, that+ conversation is rejected with ``workforce_config_changed`` on its next+ turn; a preview conversation in the workforce builder is not checked.++ A selection with more than 100 names, or a name that is empty, blank or+ longer than 100 characters, cannot be sent back unchanged. There is no+ conflict detection: of two concurrent replacements the later one wins.+ """++ model_config = ConfigDict(extra="forbid")++ connectors: list[+ Annotated[str, StringConstraints(min_length=1, max_length=100, pattern=r"\S")]+ ] = Field(+ ...,+ max_length=100,+ description=(+ "The complete new list of connector names; a name repeated "+ "exactly is kept once, at its first position. Names that fold "+ "to the same identity, such as 'Foo' and 'foo', are both kept."+ ),+ )+ all_connectors: bool = Field(+ ...,+ description=(+ "False selects only the connectors listed: the category that "+ "selects every connector is removed. True keeps that category, "+ "adding it when the agent lacks it, so the list does not narrow "+ "which connectors the agent can use; it still decides which "+ "Custom APIs are selected."+ ),+ )++class V1McpTool(BaseModel):"""One tool a connector offers."""diff --git a/src/xagent/web/services/agent_management.py b/src/xagent/web/services/agent_management.pyindex 5d5584e6a..1df69e528 100644--- a/src/xagent/web/services/agent_management.py+++ b/src/xagent/web/services/agent_management.py@@ -14,12 +14,14 @@ from sqlalchemy.engine import CursorResultfrom sqlalchemy.exc import IntegrityErrorfrom sqlalchemy.orm import Session, aliased+from ...core.tools.adapters.vibe.selection_spec import normalize_mcp_server_namefrom ...core.tools.core.document_search import find_missing_knowledge_basesfrom ...core.utils.api_key import (PREFIX_COLLISION_RETRIES,ApiKeyKind,generate_api_key,)+from ...core.utils.type_check import ensure_listfrom ...templates.manager import TemplateManagerfrom ..models.agent import (AGENT_NAME_UNIQUE_INDEX,@@ -33,7 +35,11 @@ from ..models.model import Model as DBModelfrom ..models.user import Userfrom ..models.workforce import Workforce, WorkforceAgent, WorkforceRunfrom ..schemas.agent_api_key import APIKeyGenerateResponse-from ..services.agent_store import AgentStore, invalidate_agent_cache+from ..services.agent_store import (+ AgentStore,+ UnsharedConnectorsError,+ invalidate_agent_cache,+)from .agent_team_scope import get_agent_team_scopefrom .api_keys import (AgentApiKeyService,@@ -49,6 +55,7 @@ from .db_runtime import (propagate_deferred_cancellation,run_db_io_cancellation_safe,)+from .mcp_server_management import HolderConnectorNames, holder_connector_namesfrom .skill_management import SkillManagementRuntime, is_valid_personal_skill_namefrom .workforce_access import can_edit_workforce, filter_visible_workforcesfrom .workforce_lifecycle import is_workforce_manager_removal_safe@@ -117,6 +124,33 @@ class InvalidAgentSkillNamesError(ValueError):)+class InvalidAgentConnectorsError(ValueError):+ """Raised when a connector list replacement cannot be accepted as given."""+++class AgentToolsUnconfiguredError(Exception):+ """Raised when the agent has no tool selection to read connectors from."""+++class AgentConnectorsNotSharedError(Exception):+ """Raised when a team agent would select connectors its team cannot use.++ ``connectors`` holds one ``{"name", "reason"}`` entry per connector, with+ ``reason`` one of ``not_shared``, ``disabled`` or ``unresolved``. The+ message lists at most five names, each cut to 100 characters of its+ ``repr``: the names are caller input.+ """++ def __init__(self, connectors: list[dict[str, str]]) -> None:+ self.connectors = connectors+ super().__init__(+ "The agent's team cannot use these connectors: "+ + ", ".join(repr(c["name"])[:100] for c in connectors[:5])+ + ". Share them with the team in the web app; a connector you "+ "disabled must be enabled first."+ )++def _string_list_elements(value: Any) -> list[str]:"""Filters a possibly-malformed list down to its string elements. Atemplate's agent_config.skills/tool_categories is author-provided YAML@@ -300,6 +334,70 @@ class AgentSkillsUpdateSnapshot:unresolved_for_caller: tuple[str, ...]+@dataclass(frozen=True)+class AgentConnectorsSnapshot:+ """Detached connector selection of one agent."""++ connectors: tuple[str, ...]+ all_connectors: bool+ unresolved: tuple[str, ...]+++_MCP_ENTRY_PREFIX = "mcp:"+_ALL_MCP_CATEGORY = "mcp"+++def _selected_connector_names(tool_categories: list[Any]) -> list[str]:+ """The ``<name>`` of every ``mcp:<name>`` entry, in stored order."""+ return [+ entry.split(":", 1)[1]+ for entry in tool_categories+ if isinstance(entry, str) and entry.startswith(_MCP_ENTRY_PREFIX)+ ]+++def _connector_selection(+ tool_categories: list[Any] | None, visible: frozenset[str]+) -> AgentConnectorsSnapshot:+ """What an agent's tool list selects, as the key holder sees it."""+ if tool_categories is None:+ return AgentConnectorsSnapshot((), True, ())+ names = _selected_connector_names(tool_categories)+ return AgentConnectorsSnapshot(+ connectors=tuple(names),+ all_connectors=_ALL_MCP_CATEGORY in tool_categories,+ unresolved=tuple(+ name for name in names if normalize_mcp_server_name(name) not in visible+ ),+ )+++def _relabel_unshared(+ unshared: list[Any], names: HolderConnectorNames+) -> list[dict[str, str]]:+ """Give each refused connector the reason shown to the caller.++ An entry carrying ``reason == "unresolved"`` is ``disabled`` when the name+ is one of the holder's own disabled connectors and nothing else with that+ name could be loaded for them.+ """+ labelled: list[dict[str, str]] = []+ for entry in unshared:+ name = str(entry.get("name", ""))+ reason = "not_shared"+ if entry.get("reason") == "unresolved":+ key = normalize_mcp_server_name(name)+ reason = (+ "disabled"+ if key in names.own_inactive+ and key not in names.own_active+ and key not in names.team_keys+ else "unresolved"+ )+ labelled.append({"name": name, "reason": reason})+ return labelled++@dataclass(frozen=True)class AgentWorkforceReference:workforce_id: int@@ -1223,6 +1321,168 @@ class AgentManagementRuntime:)return tuple(requested), tuple(added)+ async def get_agent_connectors(+ self,+ *,+ user_id: int,+ agent_id: int,+ ) -> AgentConnectorsSnapshot | None:+ """The connectors an agent the user can see selects, else ``None``.++ An agent on the default tool set selects every connector. Access is+ decided before any connector is read. A failure to read the visible+ connectors propagates.+ """+ return await run_db_io_cancellation_safe(+ lambda: self._get_agent_connectors_sync(user_id=user_id, agent_id=agent_id)+ )++ @staticmethod+ def _get_agent_connectors_sync(+ *, user_id: int, agent_id: int+ ) -> AgentConnectorsSnapshot | None:+ SessionLocal = get_session_local()+ with SessionLocal() as db:+ team_scope = get_agent_team_scope(db, user_id)+ agent = AgentStore(db).get_owned_agent(user_id, agent_id, team_scope)+ if agent is None:+ return None+ tool_categories = cast(+ "list[Any] | None", ensure_list(agent.tool_categories)+ )+ if tool_categories is None:+ return _connector_selection(None, frozenset())+ visible = holder_connector_names(db, user_id).visible+ return _connector_selection(tool_categories, visible)++ async def set_agent_connectors(+ self,+ *,+ user_id: int,+ key_prefix: str,+ agent_id: int,+ connectors: list[str],+ all_connectors: bool,+ ) -> AgentConnectorsSnapshot | None:+ """Replace the connectors an agent the user can see selects.++ Returns ``None`` when the user cannot see the agent. That is checked+ first, then the visible connector names are read, and then the write+ takes the agent row lock and decides on the agent as it is under that+ lock. Each of the three steps uses its own Session, and the team list+ hook is called once, in the second, while no row lock is held. Only a+ name the request adds has to be visible to the user. A failure to read+ the visible names propagates and nothing is written.+ """+ if not await run_db_io_cancellation_safe(+ lambda: self._agent_is_visible_sync(user_id=user_id, agent_id=agent_id)+ ):+ return None+ names = await run_db_io_cancellation_safe(+ lambda: self._read_holder_connector_names_sync(user_id=user_id)+ )+ return await run_db_io_cancellation_safe(+ lambda: self._set_agent_connectors_sync(+ user_id=user_id,+ key_prefix=key_prefix,+ agent_id=agent_id,+ connectors=connectors,+ all_connectors=all_connectors,+ names=names,+ )+ )++ @staticmethod+ def _agent_is_visible_sync(*, user_id: int, agent_id: int) -> bool:+ SessionLocal = get_session_local()+ with SessionLocal() as db:+ team_scope = get_agent_team_scope(db, user_id)+ agent = AgentStore(db).get_owned_agent(user_id, agent_id, team_scope)+ return agent is not None++ @staticmethod+ def _read_holder_connector_names_sync(*, user_id: int) -> HolderConnectorNames:+ SessionLocal = get_session_local()+ with SessionLocal() as db:+ return holder_connector_names(db, user_id)++ @staticmethod+ def _set_agent_connectors_sync(+ *,+ user_id: int,+ key_prefix: str,+ agent_id: int,+ connectors: list[str],+ all_connectors: bool,+ names: HolderConnectorNames,+ ) -> AgentConnectorsSnapshot | None:+ SessionLocal = get_session_local()+ with SessionLocal() as db:+ team_scope = get_agent_team_scope(db, user_id)+ store = AgentStore(db)+ agent = store.get_owned_agent(+ user_id, agent_id, team_scope, for_update=True+ )+ if agent is None:+ return None+ current: list[Any] | None = cast(+ "list[Any] | None", ensure_list(agent.tool_categories)+ )+ if current is None:+ raise AgentToolsUnconfiguredError()+ requested = list(dict.fromkeys(connectors))+ selected = list(dict.fromkeys(_selected_connector_names(current)))+ if requested == selected and all_connectors == (+ _ALL_MCP_CATEGORY in current+ ):+ return _connector_selection(current, names.visible)+ added = [name for name in requested if name not in selected]+ invisible = [+ name+ for name in added+ if normalize_mcp_server_name(name) not in names.visible+ ]+ if invisible:+ raise InvalidAgentConnectorsError(+ "These connectors are not visible to the key holder: "+ + ", ".join(repr(name)[:100] for name in invisible[:5])+ )+ kept = [+ entry+ for entry in current+ if not (isinstance(entry, str) and entry.startswith(_MCP_ENTRY_PREFIX))+ ]+ if not all_connectors:+ kept = [entry for entry in kept if entry != _ALL_MCP_CATEGORY]+ elif _ALL_MCP_CATEGORY not in kept:+ kept.append(_ALL_MCP_CATEGORY)+ replacement = kept + [f"{_MCP_ENTRY_PREFIX}{name}" for name in requested]+ try:+ store.update_agent_fields(+ user_id,+ agent_id,+ {"tool_categories": replacement},+ team_scope=team_scope,+ agent=agent,+ )+ except UnsharedConnectorsError as exc:+ raise AgentConnectorsNotSharedError(+ _relabel_unshared(exc.connectors, names)+ ) from exc+ stored = list(agent.tool_categories or [])+ removed = [name for name in selected if name not in requested]+ logger.info(+ "personal key agent connectors write: key_prefix=%s user_id=%d "+ "agent_id=%d added=%d removed=%d all_connectors=%s",+ key_prefix,+ user_id,+ agent_id,+ len(added),+ len(removed),+ all_connectors,+ )+ return _connector_selection(stored, names.visible)+@staticmethoddef _run_runtime_key_session_operation(operation: Callable[diff --git a/src/xagent/web/services/mcp_server_management.py b/src/xagent/web/services/mcp_server_management.pyindex 394093d56..764934ca4 100644--- a/src/xagent/web/services/mcp_server_management.py+++ b/src/xagent/web/services/mcp_server_management.py@@ -24,6 +24,7 @@ from __future__ import annotationsimport asyncioimport logging+from dataclasses import dataclassfrom types import SimpleNamespacefrom typing import Any, Callable, Iterable, Optional, cast@@ -32,6 +33,7 @@ from sqlalchemy import cast as sa_castfrom sqlalchemy import literal, or_from ...core.tools.adapters.vibe.connector_runtime import ConnectorRuntimeError+from ...core.tools.adapters.vibe.selection_spec import normalize_mcp_server_namefrom ...core.tools.adapters.vibe.signed_upload import signed_upload_settings_errorfrom ...core.tools.core.mcp.model import MASKED_SECRET_VALUE, SENSITIVE_AUTH_FIELDSfrom ..api.mcp import (@@ -50,6 +52,7 @@ from ..api.mcp import (delete_mcp_server,update_mcp_server,)+from ..models.custom_api import CustomApi, UserCustomApifrom ..models.database import get_session_localfrom ..models.mcp import MCPServer, UserMCPServerfrom ..models.mcp_oauth import MCPOAuthGrant@@ -118,6 +121,32 @@ def _load_holder(db: Any, user_id: int) -> User:return user+def _visible_mcp_listing(+ db: Any, user_id: int+) -> tuple[list[tuple[MCPServer, UserMCPServer | None]], dict[str, set[int]]]:+ """The rows of ``visible_mcp_server_rows`` and the team hook's answer.++ The team list hook is called exactly once. Its answer is returned whole so+ that a caller needing the Custom API half does not call it again.+ """+ own = (+ db.query(MCPServer, UserMCPServer)+ .join(UserMCPServer, UserMCPServer.mcpserver_id == MCPServer.id)+ .filter(UserMCPServer.user_id == user_id)+ .all()+ )+ own_ids = {int(server.id) for server, _link in own}+ team_shared = visible_team_connector_ids(db, user_id)+ team_ids = team_shared["mcp"] - own_ids+ team = (+ db.query(MCPServer).filter(MCPServer.id.in_(team_ids)).all() if team_ids else []+ )+ rows = [(server, link) for server, link in own] + [+ (server, None) for server in team+ ]+ return rows, team_shared++def visible_mcp_server_rows(db: Any, user_id: int) -> list[tuple[MCPServer, UserMCPServer | None]]:@@ -132,20 +161,66 @@ def visible_mcp_server_rows(A failing team hook propagates. Folding it into "the team shares nothing"would return a list that silently lacks connectors."""- own = (- db.query(MCPServer, UserMCPServer)- .join(UserMCPServer, UserMCPServer.mcpserver_id == MCPServer.id)- .filter(UserMCPServer.user_id == user_id)+ return _visible_mcp_listing(db, user_id)[0]+++@dataclass(frozen=True)+class HolderConnectorNames:+ """The folded names an agent's ``mcp:<name>`` entry can select for a holder.++ A name is folded with ``normalize_mcp_server_name``. An entry selects an+ MCP connector or a Custom API, so both are counted.++ ``visible`` is every name the holder can see. ``own_active`` and+ ``own_inactive`` are the names of the holder's own links, enabled and+ disabled. ``team_keys`` are the names of every connector the team shares,+ including one the holder also links.+ """++ visible: frozenset[str]+ own_active: frozenset[str]+ own_inactive: frozenset[str]+ team_keys: frozenset[str]+++def holder_connector_names(db: Any, user_id: int) -> HolderConnectorNames:+ """The folded connector names the holder can see, split by where they come from.++ The team list hook is called once. A failing hook propagates: an empty set+ would make every name look invisible.+ """+ rows, team_shared = _visible_mcp_listing(db, user_id)+ own_active: set[str] = set()+ own_inactive: set[str] = set()+ team_keys: set[str] = set()+ for server, link in rows:+ key = normalize_mcp_server_name(str(server.name))+ if link is None or int(server.id) in team_shared["mcp"]:+ team_keys.add(key)+ if link is not None:+ (own_active if link.is_active else own_inactive).add(key)++ own_apis = (+ db.query(CustomApi.id, CustomApi.name, UserCustomApi.is_active)+ .join(UserCustomApi, UserCustomApi.custom_api_id == CustomApi.id)+ .filter(UserCustomApi.user_id == user_id).all())- own_ids = {int(server.id) for server, _link in own}- team_ids = visible_team_connector_ids(db, user_id)["mcp"] - own_ids- team = (- db.query(MCPServer).filter(MCPServer.id.in_(team_ids)).all() if team_ids else []+ for _api_id, name, is_active in own_apis:+ (own_active if is_active else own_inactive).add(+ normalize_mcp_server_name(str(name))+ )+ team_api_ids = team_shared["custom_api"]+ if team_api_ids:+ for (name,) in db.query(CustomApi.name).filter(CustomApi.id.in_(team_api_ids)):+ team_keys.add(normalize_mcp_server_name(str(name)))++ return HolderConnectorNames(+ visible=frozenset(own_active | own_inactive | team_keys),+ own_active=frozenset(own_active),+ own_inactive=frozenset(own_inactive),+ team_keys=frozenset(team_keys),)- return [(server, link) for server, link in own] + [- (server, None) for server in team- ]def resolve_holder_connector(diff --git a/tests/web/api/v1/test_agent_connectors.py b/tests/web/api/v1/test_agent_connectors.pynew file mode 100644index 000000000..989f74ba5--- /dev/null+++ b/tests/web/api/v1/test_agent_connectors.py@@ -0,0 +1,811 @@+"""Integration tests for reading and replacing an agent's connectors over /v1."""++import logging++import pytest++from xagent.web.models.agent import Agent, AgentOrigin+from xagent.web.models.custom_api import CustomApi, UserCustomApi+from xagent.web.services import connector_team_scope, mcp_server_management+from xagent.web.services.agent_store import AgentStore+from xagent.web.services.agent_team_scope import (+ AgentTeamScope,+ set_agent_team_hooks,+)++from ..conftest import _direct_db_session, _register_second_user, client+from .test_agent_skills import _user_id, team_scopes # noqa: F401,F811+from .test_mcp_servers import ( # noqa: F401 (_no_team_hooks is an autouse fixture)+ Holder,+ _error,+ _holder,+ _no_team_hooks,+ _seed,+)++pytestmark = pytest.mark.usefixtures("_test_db")++_DEFAULT_TOOLS_MESSAGE = (+ "This agent uses the default tool set; choose its tools in the web app first."+)+++# ===== helpers =====+++def alice() -> Holder:+ holder = _holder("alice")+ _seed("crm", owner=holder)+ _seed("My-Server", owner=holder)+ _seed("ops", owner=holder)+ db = _direct_db_session()+ try:+ api = CustomApi(name="Billing API")+ db.add(api)+ db.flush()+ db.add(+ UserCustomApi(user_id=holder.user_id, custom_api_id=api.id, is_owner=True)+ )+ db.commit()+ finally:+ db.close()+ return holder+++def _seed_agent(+ owner: str,+ tool_categories,+ *,+ team_id: int | None = None,+ visibility: str = "team",+ origin: str = AgentOrigin.USER.value,+) -> int:+ db = _direct_db_session()+ try:+ agent = Agent(+ user_id=_user_id(owner),+ name=f"agent {db.query(Agent).count()}",+ tool_categories=tool_categories,+ team_id=team_id,+ visibility=visibility,+ origin=origin,+ )+ db.add(agent)+ db.commit()+ return int(agent.id)+ finally:+ db.close()+++def _stored(agent_id: int):+ db = _direct_db_session()+ try:+ return db.get(Agent, agent_id).tool_categories+ finally:+ db.close()+++def _get(holder: Holder, agent_id: int):+ return client.get(f"/v1/agents/{agent_id}/connectors", headers=holder.headers)+++def _put(holder: Holder, agent_id: int, connectors, all_connectors=False):+ body = {"connectors": connectors}+ if all_connectors is not None:+ body["all_connectors"] = all_connectors+ return client.put(+ f"/v1/agents/{agent_id}/connectors", headers=holder.headers, json=body+ )+++def _count_writes(monkeypatch) -> list[int]:+ writes: list[int] = []+ real = AgentStore.update_agent_fields++ def counted(self, user_id, agent_id, *args, **kwargs):+ writes.append(agent_id)+ return real(self, user_id, agent_id, *args, **kwargs)++ monkeypatch.setattr(AgentStore, "update_agent_fields", counted)+ return writes+++def _count_list_hook(monkeypatch, before=None) -> list[str]:+ """Record each call of the team list hook; ``before`` runs ahead of it."""+ events: list[str] = []+ real = mcp_server_management.visible_team_connector_ids++ def counted(db, user_id):+ events.append("hook")+ if before is not None:+ before()+ return real(db, user_id)++ monkeypatch.setattr(mcp_server_management, "visible_team_connector_ids", counted)+ return events+++# ===== the connectors are reachable exactly where the agent is =====++# (cell, the caller's role in team 1, how the agent is stored, reachable)+_ACCESS = [+ ("own", "member", {"owner": "alice"}, True),+ ("team-visible", "member", {"owner": "bob", "team_id": 1}, True),+ (+ "admins-only-to-a-member",+ "member",+ {"owner": "bob", "team_id": 1, "visibility": "admins"},+ False,+ ),+ (+ "admins-only-to-an-admin",+ "admin",+ {"owner": "bob", "team_id": 1, "visibility": "admins"},+ True,+ ),+ ("other-team", "admin", {"owner": "bob", "team_id": 2}, False),+ (+ "workforce-manager",+ "member",+ {"owner": "alice", "origin": AgentOrigin.WORKFORCE_GENERATED_MANAGER.value},+ False,+ ),+ ("nonexistent", "member", None, False),+]++[email protected]("method", ["GET", "PUT"])+ ("cell", "role", "stored_as", "reachable"), _ACCESS, ids=[c[0] for c in _ACCESS]+)+def test_connector_list_is_reachable_exactly_where_the_agent_is(+ cell,+ role,+ stored_as,+ reachable,+ method,+ alice,+ team_scopes, # noqa: F811+ monkeypatch,+):+ assert len(_ACCESS) == 7+ _register_second_user("bob")+ team_scopes[alice.user_id] = AgentTeamScope(+ team_id=1, is_team_admin=role == "admin"+ )+ seeded = ["basic_tools", "mcp:seeded"]+ agent_id = (+ 999_999+ if stored_as is None+ else _seed_agent(tool_categories=seeded, **stored_as)+ )+ hook_calls = _count_list_hook(monkeypatch)++ resp = _get(alice, agent_id) if method == "GET" else _put(alice, agent_id, [])++ if not reachable:+ _error(resp, 404, "agent_not_found")+ assert hook_calls == [], "access is refused before any connector is read"+ if stored_as is not None:+ assert _stored(agent_id) == seeded+ return+ assert resp.status_code == 200, resp.text+ assert hook_calls == ["hook"]+ if method == "GET":+ assert resp.json() == {+ "agent_id": agent_id,+ "connectors": ["seeded"],+ "all_connectors": False,+ "unresolved": ["seeded"],+ }+ else:+ assert _stored(agent_id) == ["basic_tools"]+++def test_agent_id_beyond_the_id_column_is_refused(alice):+ _error(_get(alice, 2**31), 422, "invalid_input")+++def test_default_tool_set_reads_as_every_connector(alice, monkeypatch):+ agent_id = _seed_agent("alice", None)+ hook_calls = _count_list_hook(monkeypatch)++ resp = _get(alice, agent_id)++ assert resp.json() == {+ "agent_id": agent_id,+ "connectors": [],+ "all_connectors": True,+ "unresolved": [],+ }+ assert hook_calls == []+++# ===== a replacement keeps order and checks only the names it adds =====++# (cell, stored before, connectors, all_connectors, status, stored after, writes,+# expected response fields or expected error)+_REPLACE = [+ (+ "default_tool_set",+ None,+ ["crm"],+ False,+ 409,+ None,+ 0,+ {"code": "agent_tools_unconfigured", "message": _DEFAULT_TOOLS_MESSAGE},+ ),+ (+ "unchanged_list_is_not_written",+ ["basic_tools", "mcp:crm", "web_tools"],+ ["crm"],+ False,+ 200,+ ["basic_tools", "mcp:crm", "web_tools"],+ 0,+ {"connectors": ["crm"]},+ ),+ (+ "invisible_added_name",+ ["basic_tools"],+ ["ghost"],+ False,+ 400,+ ["basic_tools"],+ 0,+ {+ "code": "invalid_input",+ "message": "These connectors are not visible to the key holder: 'ghost'",+ },+ ),+ (+ "custom_api_name",+ ["basic_tools"],+ ["Billing API"],+ False,+ 200,+ ["basic_tools", "mcp:Billing API"],+ 1,+ {"unresolved": []},+ ),+ (+ "folded_match",+ ["basic_tools"],+ ["my_server"],+ False,+ 200,+ ["basic_tools", "mcp:my_server"],+ 1,+ {"unresolved": []},+ ),+ (+ "invisible_old_name_is_kept",+ ["basic_tools", "mcp:gone"],+ ["gone", "crm"],+ False,+ 200,+ ["basic_tools", "mcp:gone", "mcp:crm"],+ 1,+ {"unresolved": ["gone"]},+ ),+ (+ "connector_entries_move_to_the_end",+ ["mcp:ops", "basic_tools", "web_tools"],+ ["My-Server", "ops"],+ False,+ 200,+ ["basic_tools", "web_tools", "mcp:My-Server", "mcp:ops"],+ 1,+ {},+ ),+ (+ "exact_duplicates_collapse",+ ["basic_tools"],+ ["crm", "crm"],+ False,+ 200,+ ["basic_tools", "mcp:crm"],+ 1,+ {},+ ),+ (+ "folded_duplicates_stay",+ ["basic_tools"],+ ["crm", "CRM"],+ False,+ 200,+ ["basic_tools", "mcp:crm", "mcp:CRM"],+ 1,+ {},+ ),+ (+ "unassignable_category_is_dropped",+ ["basic_tools", "other"],+ ["crm"],+ False,+ 200,+ ["basic_tools", "mcp:crm"],+ 1,+ {"connectors": ["crm"]},+ ),+ (+ "stored_duplicates_are_not_rewritten",+ ["basic_tools", "mcp:crm", "mcp:crm"],+ ["crm"],+ False,+ 200,+ ["basic_tools", "mcp:crm", "mcp:crm"],+ 0,+ {"connectors": ["crm", "crm"]},+ ),+ (+ "all_false_drops_the_category",+ ["basic_tools", "mcp"],+ ["crm"],+ False,+ 200,+ ["basic_tools", "mcp:crm"],+ 1,+ {"all_connectors": False},+ ),+ (+ "all_true_keeps_the_category",+ ["basic_tools", "mcp"],+ ["crm"],+ True,+ 200,+ ["basic_tools", "mcp", "mcp:crm"],+ 1,+ {"all_connectors": True},+ ),+ (+ "all_true_alone_is_a_change",+ ["basic_tools", "mcp:crm"],+ ["crm"],+ True,+ 200,+ ["basic_tools", "mcp", "mcp:crm"],+ 1,+ {"all_connectors": True},+ ),+ (+ "missing_all_connectors",+ ["basic_tools"],+ ["crm"],+ None,+ 422,+ ["basic_tools"],+ 0,+ {"code": "invalid_input"},+ ),+]+++ (+ "cell",+ "before",+ "names",+ "all_connectors",+ "status",+ "after",+ "writes",+ "expect",+ ),+ _REPLACE,+ ids=[r[0] for r in _REPLACE],+)+def test_replacement_keeps_order_and_checks_only_added_names(+ cell,+ before,+ names,+ all_connectors,+ status,+ after,+ writes,+ expect,+ alice,+ monkeypatch,+):+ assert len(_REPLACE) == 15+ agent_id = _seed_agent("alice", before)+ write_calls = _count_writes(monkeypatch)++ resp = _put(alice, agent_id, names, all_connectors)++ assert resp.status_code == status, resp.text+ assert _stored(agent_id) == after+ assert len(write_calls) == writes+ if status == 200:+ body = resp.json()+ assert body["agent_id"] == agent_id+ assert {k: body[k] for k in expect} == expect+ else:+ error = _error(resp, status, expect["code"])+ if "message" in expect:+ assert error["message"] == expect["message"]+++ "names",+ [[f"c{i}" for i in range(101)], ["x" * 101], [""], [" "]],+ ids=["over_100_items", "name_over_100_chars", "empty_name", "blank_name"],+)+def test_oversized_or_empty_names_are_refused(names, alice):+ agent_id = _seed_agent("alice", ["basic_tools"])+ _error(_put(alice, agent_id, names), 422, "invalid_input")+ assert _stored(agent_id) == ["basic_tools"]+++def test_refusal_lists_five_names_and_cuts_each_to_100_characters(alice):+ agent_id = _seed_agent("alice", ["basic_tools"])+ names = ["y" * 100, "a1", "a2", "a3", "a4", "a5"]++ error = _error(_put(alice, agent_id, names), 400, "invalid_input")++ assert error["message"] == (+ "These connectors are not visible to the key holder: "+ + ", ".join(repr(name)[:100] for name in names[:5])+ )+ assert _stored(agent_id) == ["basic_tools"]+++def test_connectors_and_custom_apis_shared_by_the_team_count_as_visible(alice):+ other = _holder("bob")+ server_id = _seed("team-crm", owner=other)+ db = _direct_db_session()+ try:+ api = CustomApi(name="Team API")+ db.add(api)+ db.flush()+ db.add(+ UserCustomApi(user_id=other.user_id, custom_api_id=api.id, is_owner=True)+ )+ db.commit()+ api_id = int(api.id)+ finally:+ db.close()+ connector_team_scope.set_connector_team_hooks(+ visibility=lambda _db, _user_id: {+ "mcp": {server_id},+ "custom_api": {api_id},+ }+ )+ agent_id = _seed_agent("alice", ["basic_tools"])++ resp = _put(alice, agent_id, ["team-crm", "Team API"])++ assert resp.status_code == 200, resp.text+ assert resp.json()["unresolved"] == []+ assert _stored(agent_id) == ["basic_tools", "mcp:team-crm", "mcp:Team API"]+++def test_a_tool_list_stored_as_text_is_read_and_written_as_a_list(alice):+ agent_id = _seed_agent("alice", '["basic_tools", "mcp:crm"]')++ got = _get(alice, agent_id)+ assert got.status_code == 200, got.text+ assert got.json()["connectors"] == ["crm"]++ resp = _put(alice, agent_id, ["crm", "ops"])++ assert resp.status_code == 200, resp.text+ assert _stored(agent_id) == ["basic_tools", "mcp:crm", "mcp:ops"]+++# ===== a team agent's selection is validated by the team =====+++def _team_agent(alice, validator, before=("basic_tools", "mcp:crm")) -> int:+ _register_second_user("bob")+ set_agent_team_hooks(+ scope=lambda _db, user_id: (+ AgentTeamScope(team_id=1, is_team_admin=False)+ if user_id == alice.user_id+ else None+ ),+ connector_validator=validator,+ )+ return _seed_agent("bob", list(before), team_id=1)+++def _clear_agent_team_hooks():+ yield+ set_agent_team_hooks()+++def _refusal(details_connectors, message_names):+ return {+ "connectors": details_connectors,+ "message": "The agent's team cannot use these connectors: "+ + message_names+ + ". Share them with the team in the web app; a connector you disabled "+ "must be enabled first.",+ }+++def _unshared_unless_all(_db, _user_id, _team_id, categories):+ return [{"type": "mcp", "id": 2, "name": "other"}] if "mcp" in categories else []+++_REFUSALS = [+ (+ "each_connector_gets_a_reason",+ lambda *_: [+ {"type": "mcp", "id": 1, "name": "x"},+ {"type": "mcp", "name": "y", "reason": "unresolved"},+ ],+ [],+ False,+ _refusal(+ [+ {"name": "x", "reason": "not_shared"},+ {"name": "y", "reason": "unresolved"},+ ],+ "'x', 'y'",+ ),+ ),+ (+ "own_disabled_connector",+ lambda *_: [{"type": "mcp", "name": "crm-off", "reason": "unresolved"}],+ ["crm-off"],+ False,+ _refusal([{"name": "crm-off", "reason": "disabled"}], "'crm-off'"),+ ),+ (+ "disabled_but_enabled_under_a_folded_twin",+ lambda *_: [{"type": "mcp", "name": "crm-off", "reason": "unresolved"}],+ ["crm-off"],+ False,+ _refusal([{"name": "crm-off", "reason": "unresolved"}], "'crm-off'"),+ ),+ (+ "disabled_but_shared_by_the_team",+ lambda *_: [{"type": "mcp", "name": "crm-off", "reason": "unresolved"}],+ ["crm-off"],+ False,+ _refusal([{"name": "crm-off", "reason": "unresolved"}], "'crm-off'"),+ ),+ (+ "disabled_but_the_team_shares_the_same_server",+ lambda *_: [{"type": "mcp", "name": "crm-off", "reason": "unresolved"}],+ ["crm-off"],+ False,+ _refusal([{"name": "crm-off", "reason": "unresolved"}], "'crm-off'"),+ ),+ (+ "disabled_but_the_team_shares_the_same_custom_api",+ lambda *_: [{"type": "custom_api", "name": "Off API", "reason": "unresolved"}],+ ["Off API"],+ False,+ _refusal([{"name": "Off API", "reason": "unresolved"}], "'Off API'"),+ ),+ (+ "unknown_reason_reads_as_not_shared",+ lambda *_: [{"type": "mcp", "name": "x", "reason": "something_new"}],+ [],+ False,+ _refusal([{"name": "x", "reason": "not_shared"}], "'x'"),+ ),+ (+ "all_connectors_adds_the_category",+ _unshared_unless_all,+ ["crm"],+ True,+ _refusal([{"name": "other", "reason": "not_shared"}], "'other'"),+ ),+]+++ ("cell", "validator", "names", "all_connectors", "expect"),+ _REFUSALS,+ ids=[r[0] for r in _REFUSALS],+)[email protected]("_clear_agent_team_hooks")+def test_team_agent_refusal_lists_each_connector_with_a_reason(+ cell, validator, names, all_connectors, expect, alice+):+ assert len(_REFUSALS) == 8+ own_off_id = _seed("crm-off", owner=alice, is_active=False)+ if cell == "disabled_but_enabled_under_a_folded_twin":+ _seed("CRM_off", owner=alice)+ if cell == "disabled_but_shared_by_the_team":+ shared_id = _seed("CRM_off")+ connector_team_scope.set_connector_team_hooks(+ visibility=lambda _db, _user_id: {+ "mcp": {shared_id},+ "custom_api": set(),+ }+ )+ if cell == "disabled_but_the_team_shares_the_same_server":+ connector_team_scope.set_connector_team_hooks(+ visibility=lambda _db, _user_id: {+ "mcp": {own_off_id},+ "custom_api": set(),+ }+ )+ if cell == "disabled_but_the_team_shares_the_same_custom_api":+ db = _direct_db_session()+ try:+ api = CustomApi(name="Off API")+ db.add(api)+ db.flush()+ db.add(+ UserCustomApi(+ user_id=alice.user_id,+ custom_api_id=api.id,+ is_owner=True,+ is_active=False,+ )+ )+ db.commit()+ own_off_api_id = int(api.id)+ finally:+ db.close()+ connector_team_scope.set_connector_team_hooks(+ visibility=lambda _db, _user_id: {+ "mcp": set(),+ "custom_api": {own_off_api_id},+ }+ )+ seen: list[list[str]] = []++ def recording(db, user_id, team_id, categories):+ seen.append(list(categories))+ return validator(db, user_id, team_id, categories)++ agent_id = _team_agent(alice, recording)++ error = _error(+ _put(alice, agent_id, names, all_connectors), 400, "connector_not_shared"+ )++ assert error["details"] == {"connectors": expect["connectors"]}+ assert error["message"] == expect["message"]+ assert ("mcp" in seen[-1]) == all_connectors+ assert _stored(agent_id) == ["basic_tools", "mcp:crm"]+++# ===== the visible names are read before the agent row is locked =====+++def test_visible_names_are_read_before_the_agent_row_is_locked(alice, monkeypatch):+ agent_id = _seed_agent("alice", ["basic_tools"])+ events: list[tuple] = []+ real = AgentStore.get_owned_agent++ def spy(self, *args, **kwargs):+ events.append(("agent", kwargs.get("for_update", False)))+ return real(self, *args, **kwargs)++ monkeypatch.setattr(AgentStore, "get_owned_agent", spy)+ _count_list_hook(monkeypatch, before=lambda: events.append(("hook",)))++ assert _put(alice, agent_id, ["crm"]).status_code == 200+ assert events == [("agent", False), ("hook",), ("agent", True)]+++def test_access_is_checked_before_the_visible_names_are_read(alice, monkeypatch):+ hook_calls = _count_list_hook(monkeypatch)++ _error(_put(alice, 999_999, ["crm"]), 404, "agent_not_found")+ _error(_get(alice, 999_999), 404, "agent_not_found")+ assert hook_calls == []+++def test_an_agent_deleted_while_names_are_read_is_not_found(alice, monkeypatch):+ agent_id = _seed_agent("alice", ["basic_tools"])++ def delete_agent():+ db = _direct_db_session()+ try:+ db.query(Agent).filter(Agent.id == agent_id).delete()+ db.commit()+ finally:+ db.close()++ writes = _count_writes(monkeypatch)+ _count_list_hook(monkeypatch, before=delete_agent)++ _error(_put(alice, agent_id, ["crm"]), 404, "agent_not_found")+ assert writes == []+++def test_the_write_decides_on_the_agent_as_it_is_under_the_lock(alice, monkeypatch):+ agent_id = _seed_agent("alice", ["basic_tools"])++ def another_edit():+ db = _direct_db_session()+ try:+ db.get(Agent, agent_id).tool_categories = ["basic_tools", "web_tools"]+ db.commit()+ finally:+ db.close()++ _count_list_hook(monkeypatch, before=another_edit)++ assert _put(alice, agent_id, ["crm"]).status_code == 200+ assert _stored(agent_id) == ["basic_tools", "web_tools", "mcp:crm"]+++# ===== a failing visibility read is not an empty set =====++[email protected]("method", ["GET", "PUT"])+def test_a_failing_visibility_read_is_not_an_empty_set(method, alice):+ agent_id = _seed_agent("alice", ["basic_tools"])++ def failing(_db, _user_id):+ raise RuntimeError("team backend exploded")++ connector_team_scope.set_connector_team_hooks(visibility=failing)++ resp = _get(alice, agent_id) if method == "GET" else _put(alice, agent_id, ["crm"])++ _error(resp, 500, "internal_error")+ assert _stored(agent_id) == ["basic_tools"]+++# ===== a write leaves one log line =====++[email protected]("_clear_agent_team_hooks")+def test_a_failing_team_validator_writes_nothing(alice, monkeypatch):+ def failing(*_args):+ raise RuntimeError("team backend exploded")++ agent_id = _team_agent(alice, failing)+ writes = _count_writes(monkeypatch)++ _error(_put(alice, agent_id, ["crm", "ops"]), 500, "internal_error")+ assert writes == [agent_id]+ assert _stored(agent_id) == ["basic_tools", "mcp:crm"]++[email protected]("outcome", ["written", "unchanged", "refused", "not_shared"])[email protected]("_clear_agent_team_hooks")+def test_a_write_logs_one_line_without_names(outcome, alice, caplog):+ _seed("zz-secret-conn", owner=alice)+ _seed("zz-other-conn", owner=alice)+ before = ["basic_tools", "mcp:crm", "mcp:ops"]+ if outcome == "not_shared":+ agent_id = _team_agent(+ alice,+ lambda *_: [{"type": "mcp", "id": 2, "name": "zz-secret-conn"}],+ before=before,+ )+ else:+ agent_id = _seed_agent("alice", before)+ names = {+ "written": ["ops", "zz-secret-conn", "zz-other-conn"],+ "unchanged": ["crm", "ops"],+ "refused": ["zz-unseen-conn"],+ "not_shared": ["crm", "ops", "zz-secret-conn"],+ }[outcome]+ caplog.clear()++ with caplog.at_level(logging.INFO):+ resp = _put(alice, agent_id, names)++ assert resp.status_code == (400 if outcome in ("refused", "not_shared") else 200), (+ resp.text+ )+ lines = [+ r.getMessage()+ for r in caplog.records+ if r.getMessage().startswith("personal key agent connectors write:")+ ]+ if outcome != "written":+ assert lines == []+ return+ prefix = alice.key.split("_")[2]+ assert lines == [+ f"personal key agent connectors write: key_prefix={prefix} "+ f"user_id={alice.user_id} agent_id={agent_id} added=2 removed=1 "+ "all_connectors=False"+ ]+ assert "secret" not in "\n".join(r.getMessage() for r in caplog.records)diff --git a/tests/web/api/v1/test_mcp_servers.py b/tests/web/api/v1/test_mcp_servers.pyindex 18db21d00..68b2c2c86 100644--- a/tests/web/api/v1/test_mcp_servers.py+++ b/tests/web/api/v1/test_mcp_servers.py@@ -13,6 +13,7 @@ from sqlalchemy.exc import OperationalErrorfrom xagent.core.tools.adapters.vibe.signed_upload import signed_upload_settings_errorfrom xagent.core.tools.core.mcp.model import MASKED_SECRET_VALUE, SENSITIVE_AUTH_FIELDSfrom xagent.web.api.mcp import TransportFieldValidator+from xagent.web.api.v1 import agents as agents_routesfrom xagent.web.api.v1 import mcp_servers as mcp_servers_routesfrom xagent.web.api.v1.errors import _DEFAULT_MESSAGES, V1ErrorCodefrom xagent.web.models.custom_api import CustomApi, UserCustomApi@@ -227,10 +228,21 @@ def _own_routes() -> list[tuple[str, str]]:)+def _agent_connector_routes() -> list[tuple[str, str]]:+ return sorted(+ (method, f"/v1{route.path}")+ for route in agents_routes.router.routes+ if route.path.endswith("/connectors") # type: ignore[attr-defined]+ for method in route.methods # type: ignore[attr-defined]+ )++@pytest.mark.parametrize("kind", _KEY_KINDS)@pytest.mark.parametrize(("method", "path"),[+ ("GET", "/v1/agents/{agent_id}/connectors"),+ ("PUT", "/v1/agents/{agent_id}/connectors"),("GET", "/v1/mcp-servers"),("GET", "/v1/mcp-servers/{server_id}"),("POST", "/v1/mcp-servers"),@@ -250,10 +262,16 @@ def test_mcp_routes_accept_only_personal_keys(method, path, kind):("POST", "/v1/mcp-servers"),("PUT", "/v1/mcp-servers/{server_id}/enabled"),]+ assert _agent_connector_routes() == [+ ("GET", "/v1/agents/{agent_id}/connectors"),+ ("PUT", "/v1/agents/{agent_id}/connectors"),+ ]bodies = {"POST": _create_body(), "PUT": {"enabled": True}, "PATCH": {}}+ if path.endswith("/connectors"):+ bodies["PUT"] = {"connectors": [], "all_connectors": False}resp = client.request(method,- path.replace("{server_id}", "1"),+ path.replace("{server_id}", "1").replace("{agent_id}", "1"),headers=_headers_for(kind),json=bodies.get(method),)diff --git a/tests/web/api/v1/test_personal_key_principal_policy.py b/tests/web/api/v1/test_personal_key_principal_policy.pyindex 2fd0228dd..f45029a4b 100644--- a/tests/web/api/v1/test_personal_key_principal_policy.py+++ b/tests/web/api/v1/test_personal_key_principal_policy.py@@ -129,9 +129,9 @@ def test_personal_key_policy_runs_only_after_the_key_verifies() -> None:@pytest.mark.usefixtures("_template_manager")def test_personal_key_policy_applies_to_every_personal_key_route() -> None:routes = _personal_key_routes()- # The 22 management routes (me, agents, templates, skills, MCP connectors), the 12- # /v1/chat task routes and the features route.- assert len(routes) == 35, routes+ # The 24 management routes (me, agents, templates, skills, MCP connectors, agent+ # connectors), the 12 /v1/chat task routes and the features route.+ assert len(routes) == 37, routesheaders = _bearer(_create_personal_key()[0])for method, template in routes:diff --git a/tests/web/api/v1/test_status_only_projection.py b/tests/web/api/v1/test_status_only_projection.pyindex 2b62912ed..e0e39592b 100644--- a/tests/web/api/v1/test_status_only_projection.py+++ b/tests/web/api/v1/test_status_only_projection.py@@ -337,6 +337,8 @@ EXCLUDE = {("POST", "/v1/agents/{agent_id}/api-key"),("GET", "/v1/agents/{agent_id}/skills"),("PUT", "/v1/agents/{agent_id}/skills"),+ ("GET", "/v1/agents/{agent_id}/connectors"),+ ("PUT", "/v1/agents/{agent_id}/connectors"),("GET", "/v1/skills"),("GET", "/v1/skills/{name}"),("POST", "/v1/skills"),