Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion src/agent_comms/cli_bridges/cli_protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@

from agent_comms.cli_bridges.wire_models import DeclaredWireFamily, WireModel
from agent_comms.coordination.errors import CoordinationReadUnavailable
from agent_comms.errors import RelationViolationError
from agent_comms.errors import RelationViolationError, UnexposedToolError
from agent_comms.execution.turn_item import NativeTurnId, TurnItem
from agent_comms.nominal.declared_family import UnknownFamilyMember
from agent_comms.nominal.field_codec import TimestampText
Expand Down Expand Up @@ -195,6 +195,12 @@ class HeldCoreError(CoreError, declared_name="held"):
exception_type = MaintenanceHeldError


class UnexposedCoreError(CoreError, declared_name="unexposed"):
"""The connector exposes no such tool to this caller (`UnexposedToolError`)."""

exception_type = UnexposedToolError


class FailedCoreError(CoreError, declared_name="failed"):
exception_type = BaseException

Expand Down
7 changes: 7 additions & 0 deletions src/agent_comms/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,13 @@ class RelationViolationError(ValueError, DrainUnavailable):
"""A required relation between declarations cannot be proved."""


class UnexposedToolError(ToolRefusedError, RelationViolationError):
"""The connector exposes no tool by this name to this caller: a bus older than the tool,
or a grant that leaves it out. A client asks `CoreAccess.serves` before a call it can do
without; this is the refusal a stale answer meets. Still a RelationViolationError, as every
refusal decoded before it was."""


class ThreadNotVisibleError(RelationViolationError, RejectedEnforcementError):
"""A direct target refused publication before a standing-rule action could apply."""

Expand Down
11 changes: 9 additions & 2 deletions src/agent_comms/transport/mcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@

from agent_comms.cli_bridges.cli_protocol import CoreError
from agent_comms.coordination.errors import CommandFailure, Refused
from agent_comms.errors import UnexposedToolError
from agent_comms.nominal.declared_family import DeclaredFamily
from agent_comms.nominal.field_codec import (
FieldCodec,
Expand All @@ -43,7 +44,6 @@
)
from agent_comms.transport.request import ToolCall, ToolRequest
from agent_comms.transport.tool_request import ServedRequest
from agent_comms_hooks import ToolRefusedError

JsonRpcId = int | str
PROTOCOL_VERSION = "2025-06-18"
Expand Down Expand Up @@ -515,7 +515,7 @@ async def result(
tool = caller.exposed().get(self.params.name)
if tool is None:
return ToolsCallResult.failed(
ToolRefusedError(f"The connector exposes no tool {self.params.name!r}.")
UnexposedToolError(f"The connector exposes no tool {self.params.name!r}.")
)
try:
answered = await connector.call(tool, self.params.arguments, caller, observer)
Expand Down Expand Up @@ -567,6 +567,13 @@ def failed(cls, error: Exception) -> ToolsCallResult:
return cls((TextContent(CoreError.from_exception(error).model_dump_json()),), True)


@dataclass(frozen=True)
class ToolsListReply(McpReply):
"""The tools/list answer: the tools this connector exposes to the caller who asked."""

result: ToolsListResult


@dataclass(frozen=True)
class ToolsCallReply(McpReply, StreamedEvent):
result: ToolsCallResult
Expand Down
24 changes: 23 additions & 1 deletion src/agent_comms/transport/remote_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@
StreamedLine,
ToolsCallMessage,
ToolsCallReply,
ToolsListMessage,
ToolsListReply,
)
from agent_comms.transport.progress import WireExportCancelled
from agent_comms.transport.request import (
Expand Down Expand Up @@ -237,6 +239,11 @@ def exchange[R: ToolResult](
) -> dict[str, JsonValue]:
"""One round trip on this thread's kept connection, so a call pays no new handshake."""
envelope = ToolsCallMessage(jsonrpc="2.0", id=1, params=request.called())
return FieldCodec.decode(ToolsCallReply, json.loads(self.round_trip(envelope))).structured()

def round_trip(self, envelope: object) -> bytes:
"""One JSON-RPC message posted on this thread's kept connection, and its reply's bytes.
A dropped connection may be a restarted connector, which may serve other tools."""
body = FieldCodec.compact(FieldCodec.encode(envelope)).encode()
connection = self.connections.connection
try:
Expand All @@ -245,13 +252,28 @@ def exchange[R: ToolResult](
payload = response.read()
except (OSError, http.client.HTTPException) as error:
connection.close()
self.forget_served()
raise ConnectionDropped(
f"The connection to {self.endpoint.url.host} dropped: {error}") from error
if response.status >= 400:
raise urllib.error.HTTPError(
str(self.endpoint.url), response.status, response.reason, response.headers,
io.BytesIO(payload))
return FieldCodec.decode(ToolsCallReply, json.loads(payload)).structured()
return payload

@cached_property
def served_tools(self) -> frozenset[str]:
"""The names of the tools this connector exposes to this caller, listed once per
connection: an older bus lists only the tools it had."""
reply = FieldCodec.decode(ToolsListReply, json.loads(
self.round_trip(ToolsListMessage(jsonrpc="2.0", id=1))))
return frozenset(tool.name for tool in reply.result.tools)

def serves(self, request_type: type[ToolRequest]) -> bool:
return request_type.declared_name in self.served_tools

def forget_served(self) -> None:
self.__dict__.pop("served_tools", None)

def post_observed[R: ToolResult](self, request: ObservedRequest[R]) -> dict[str, JsonValue]:
"""A call the client asked progress for: its events reach the request's observer, and a
Expand Down
34 changes: 34 additions & 0 deletions src/agent_comms/transport/request.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from typing_extensions import TypeVarTuple

from agent_comms.coordination.errors import CoordinationReadUnavailable
from agent_comms.errors import UnexposedToolError
from agent_comms.nominal.declared_family import DeclaredFamily
from agent_comms.nominal.field_codec import (
ArgumentsExclude,
Expand Down Expand Up @@ -225,6 +226,25 @@ def __new__(cls, *args: object) -> Self:
return ConnectionError.__new__(cls, *args)


class OptionalRead[Result: ToolResult = ToolResult](ReadRequest[Result], declared_name=None):
"""A read its caller can do without. A Core that does not serve it (a bus older than the
tool, or a grant that leaves it out) answers `absent()`, the read's declared nothing,
never a refusal: a newer client on an older bus draws what that bus has."""

@abstractmethod
def absent(self) -> Result:
"""What this read answers from a Core that does not serve it."""

def posted(self, remote: RequestPoster) -> dict[str, JsonValue]:
if remote.serves(type(self)):
try:
return super().posted(remote)
except UnexposedToolError:
# The connector changed since its tools were listed: list them again next time.
remote.forget_served()
return cast(dict[str, JsonValue], FieldCodec.encode(self.absent()))


@dataclass(frozen=True, kw_only=True)
class ThreadReadRequest[Result: ToolResult = ToolResult](ReadRequest[Result], declared_name=None):
"""A read about one thread; empty names the caller's own."""
Expand Down Expand Up @@ -254,6 +274,14 @@ def post_observed[R: ToolResult](
self, request: ObservedRequest[R],
) -> dict[str, JsonValue]: ...

@abstractmethod
def serves(self, request_type: type[ToolRequest]) -> bool:
"""Whether the Core across the connector serves this request to this caller."""

@abstractmethod
def forget_served(self) -> None:
"""What the connector serves is asked again on the next `serves`."""


class CoreAccess(ABC):
"""Where a UI's Core requests are answered: in this process or across the connector. The
Expand All @@ -262,3 +290,9 @@ class CoreAccess(ABC):
@abstractmethod
def call[R: ToolResult](self, request: ToolRequest[R]) -> R:
"""The request's declared result, from whichever Core this access reaches."""

def serves(self, request_type: type[ToolRequest]) -> bool:
"""Whether this Core answers `request_type`. A Core in this process serves every request
it declares; a Core across a connector (`RemoteCoreAccess`) answers from the tools that
connector exposes to this caller."""
return True
9 changes: 7 additions & 2 deletions src/agent_comms/transport/tools/sidebar.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@
from agent_comms.registry.threads import Thread
from agent_comms.transport.request import (
ObservedRequest,
OptionalRead,
ReadRequest,
ToolRequest,
tool_field,
Expand Down Expand Up @@ -615,8 +616,9 @@ class MessageFileRead:


@dataclass(frozen=True, kw_only=True)
class CommsMessageFilesTool(MessageFileRead, ReadRequest[MessageFilesRead]):
"""The files a page's messages carry, read beside the page; the page itself never names them."""
class CommsMessageFilesTool(MessageFileRead, OptionalRead[MessageFilesRead]):
"""The files a page's messages carry, read beside the page; the page itself never names them.
A bus older than message files carries none, so its pages list none."""

label = "Message files"
description = (
Expand All @@ -625,6 +627,9 @@ class CommsMessageFilesTool(MessageFileRead, ReadRequest[MessageFilesRead]):
messages: Annotated[
tuple[MessageReference, ...], *tool_field("The messages whose files to list")]

def absent(self) -> MessageFilesRead:
return MessageFilesRead(files=())


@dataclass(frozen=True, kw_only=True)
class CommsMessageFileTool(MessageFileRead, ReadRequest[MessageFileContent]):
Expand Down
115 changes: 115 additions & 0 deletions tests/test_connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
from contextlib import contextmanager, suppress
from dataclasses import dataclass, field, replace
from pathlib import Path
from types import SimpleNamespace
from urllib.parse import parse_qs, urlsplit

import pytest
Expand Down Expand Up @@ -76,6 +77,7 @@
from agent_comms.transport.connector_caller import (
CALLER,
ActingFork,
ConnectorCaller,
GrantRefusedError,
ReadOnlyConnectorCaller,
ScopedUiCaller,
Expand All @@ -84,7 +86,9 @@
)
from agent_comms.transport.connector_profile import (
OBSERVE_PATH,
BearerSecret,
HttpsMcpEndpoint,
UiCredential,
UiConnectionProfile,
UiGrantId,
UiGrantSummary,
Expand Down Expand Up @@ -134,8 +138,12 @@
ServedCommsUserSendTool,
invoke_tool,
)
from agent_comms.errors import RelationViolationError, UnexposedToolError
from agent_comms.transport.remote_core import RemoteCoreAccess
from agent_comms.transport.tools.sidebar import (
CommsConversationPageTool,
CommsMessageFilesTool,
CommsMessageFileTool,
CommsConversationRevisionTool,
CommsExportWireTool,
CommsLatestSequenceTool,
Expand Down Expand Up @@ -1590,3 +1598,110 @@ async def stuck_handler_nested() -> None:
connector.running_requests.pop(task, None)
held.set()
await task


class ForwardingConnection:
"""RemoteCoreAccess's kept connection, posting each request to the connector under test from
the worker thread the access runs on, as the real client does over TLS."""

def __init__(self, client: TestClient, loop: asyncio.AbstractEventLoop, token: str) -> None:
self.client, self.loop, self.token, self.methods = client, loop, token, []

def request(self, method, path, body, headers) -> None:
message = json.loads(body)
self.methods.append(f'{message["method"]}:{message.get("params", {}).get("name", "")}')
posted = self.client.post(path, data=body, headers={
"Authorization": f"Bearer {self.token}", "Content-Type": "application/json"})
self.reply = asyncio.run_coroutine_threadsafe(self.read(posted), self.loop)

@staticmethod
async def read(posted):
response = await posted
return response.status, await response.read()

def getresponse(self):
status, payload = self.reply.result(timeout=30)

class Reply:
reason, headers = "", {}

def read(self) -> bytes:
return payload
reply = Reply()
reply.status = status
return reply

def close(self) -> None:
pass


FILE_TOOLS = (CommsMessageFilesTool.declared_name, CommsMessageFileTool.declared_name)


@pytest.fixture
def older_connector(monkeypatch):
"""The connector a bus older than message files runs: it exposes every tool but those."""
exposed = ConnectorCaller.exposed

def without_files(self):
return {name: tool for name, tool in exposed(self).items()
if name not in FILE_TOOLS}
monkeypatch.setattr(ConnectorCaller, "exposed", without_files)


async def remote_access(
client: TestClient, comms: Comms,
) -> tuple[RemoteCoreAccess, ForwardingConnection]:
access = RemoteCoreAccess(
HttpsMcpEndpoint(URL("https://core.example/mcp")),
UiCredential(UiGrantId("1" * 32), RootId("a" * 32), 2**31, BearerSecret("token")))
token = await approved_token(client, comms)
connection = ForwardingConnection(client, asyncio.get_running_loop(), token)
# The kept connection is per thread; the calls below run on a worker thread, so every
# thread is given this one.
access.__dict__["connections"] = SimpleNamespace(connection=connection)
return access, connection


FILES = CommsMessageFilesTool(conversation="#comms", messages=())


async def test_a_newer_client_reads_no_files_from_a_bus_without_them(
client, comms, older_connector,
):
"""The page read a newer client makes beside every page answers its declared nothing from
a bus older than message files, and is never posted there: the tools are listed once."""
access, connection = await remote_access(client, comms)
assert not await asyncio.to_thread(access.serves, CommsMessageFilesTool)
assert await asyncio.to_thread(access.call, FILES) == FILES.absent()
assert await asyncio.to_thread(access.call, FILES) == FILES.absent()
assert connection.methods == ["tools/list:"]


async def test_a_bus_with_files_answers_the_read(client, comms):
access, connection = await remote_access(client, comms)
assert await asyncio.to_thread(access.serves, CommsMessageFilesTool)
assert (await asyncio.to_thread(access.call, FILES)).files == ()
assert connection.methods == ["tools/list:", "tools/call:comms_message_files"]


async def test_a_stale_tool_list_meets_a_typed_refusal_and_lists_again(
client, comms, older_connector,
):
"""A list read before the connector changed: the call is refused as unexposed, by type, so
the optional read answers its nothing and the next `serves` lists the tools again."""
access, connection = await remote_access(client, comms)
access.__dict__["served_tools"] = frozenset({CommsMessageFilesTool.declared_name})
assert await asyncio.to_thread(access.call, FILES) == FILES.absent()
assert "served_tools" not in access.__dict__
assert not await asyncio.to_thread(access.serves, CommsMessageFilesTool)
assert connection.methods == ["tools/call:comms_message_files", "tools/list:"]


async def test_an_unexposed_tool_is_refused_as_unexposed(client, comms, older_connector):
"""Posted anyway, a call to a tool the connector does not expose is refused by type, and
every earlier handler of a refusal (RelationViolationError) still catches it."""
access, _ = await remote_access(client, comms)
with pytest.raises(UnexposedToolError) as refused:
await asyncio.to_thread(access.exchange, FILES)
assert isinstance(refused.value, RelationViolationError)
Loading