fix(agent): stop tool calls on Stop, always allow app tools, name databases on cards (#6890)

* fix(agent): stop tool calls on Stop, always allow app tools, name databases on cards

Stop is seen only on the 2 s lease poll, Always allow skipped connected-app
tools, and same-named tables and rows looked identical on approval cards.

* fix(agent): give every named row its id when row labels repeat

A row named like another row's label could still read the same.

* fix: address review on agent stop, MCP always allow and database names

Refused calls show as not run, Always allow on MCP tools respects switched-off
servers and tools under lock, and more presentations name the database.
This commit is contained in:
alamin-br authored and GitHub committed 2026-11-27 10:09:24 +01:00
1 parent 0545545bca
commit 3276ed06fb
18 files changed
+543 -79

No files matched your search

@@ -25,15 +25,16 @@ def table_reference(
"""
:param ctx: The Agent identity and its workspace.
:param table_id: A table the call names.
:return: The table and its name when the identity can see it, else None and
its ID as written, so the tool's own error explains it.
:return: The table, with its database's name and its own when the identity
can see it, as a duplicated database keeps every table's name. Else None
and its ID as written, so the tool's own error explains it.
"""
tables = TableHandler().list_workspace_tables(ctx.user, ctx.workspace)
table = tables.filter(id=table_id).first()
table = tables.select_related("database").filter(id=table_id).first()
if table is None:
return None, {"table_id": table_id}
return table, {"table": table.name}
return table, {"database": table.database.name, "table": table.name}
def table_names(ctx: ToolContext, table_ids: list[int]) -> dict[int, str]:
@@ -47,6 +48,21 @@ def table_names(ctx: ToolContext, table_ids: list[int]) -> dict[int, str]:
return dict(tables.filter(id__in=table_ids).values_list("id", "name"))
def database_name(ctx: ToolContext, table_ids: list[int]) -> str | None:
"""
:param ctx: The Agent identity and its workspace.
:param table_ids: Tables a call worked on.
:return: The name of the one database the identity sees them in, or None
when they are in several or none.
"""
tables = TableHandler().list_workspace_tables(ctx.user, ctx.workspace)
names = set(
tables.filter(id__in=table_ids).values_list("database__name", flat=True)
)
return names.pop() if len(names) == 1 else None
def database_reference(ctx: ToolContext, database_id: int) -> dict[str, Any]:
"""
:param ctx: The Agent identity and its workspace.
@@ -60,20 +76,24 @@ def database_reference(ctx: ToolContext, database_id: int) -> dict[str, Any]:
return {"database_id": database_id}
def named_fields(ctx: ToolContext, field_ids: list[int]) -> dict[int, tuple[str, str]]:
def named_fields(
ctx: ToolContext, field_ids: list[int]
) -> dict[int, tuple[str, str, str]]:
"""
Resolve each field on its own, so two fields with the same name stay apart.
:param ctx: The Agent identity and its workspace.
:param field_ids: Fields the call names.
:return: Each field's name and its table's name, by field ID, for the fields
the identity can see. The others keep their IDs, so the tool's own error
explains them.
:return: Each field's, its table's and its database's name, by field ID, for
the fields the identity can see. The others keep their IDs, so the tool's
own error explains them.
"""
listed = TableHandler().list_workspace_tables(ctx.user, ctx.workspace)
found = list(
Field.objects.filter(id__in=field_ids, table__in=listed).select_related("table")
Field.objects.filter(id__in=field_ids, table__in=listed).select_related(
"table__database"
)
)
tables = {found_field.table_id: found_field.table for found_field in found}
permitted = {
@@ -83,7 +103,11 @@ def named_fields(ctx: ToolContext, field_ids: list[int]) -> dict[int, tuple[str,
)
}
return {
found_field.id: (found_field.name, found_field.table.name)
found_field.id: (
found_field.name,
found_field.table.name,
found_field.table.database.name,
)
for found_field in found
if found_field.table_id in permitted
}
@@ -122,11 +146,18 @@ def row_names(ctx: ToolContext, table: Table, row_ids: list[int]) -> dict[int, s
:param table: A table the identity can see.
:param row_ids: Rows the call names.
:return: Each row's primary value as text, or ``unnamed row <id>`` when it's
empty, by row ID. Rows that are missing or trashed, and all rows when the
identity may not list them, keep their IDs.
empty, by row ID. When two of them read the same, every named row gets its
ID too, which no other row's label can match. Rows that are missing or
trashed, and all rows when the identity may not list them, keep their IDs.
"""
if not permitted_tables(ctx, [table], ListRowsDatabaseTableOperationType.type):
return {}
names = RowHandler().get_row_names(table, row_ids)
return {row_id: name or f"unnamed row {row_id}" for row_id, name in names.items()}
labels = {row_id: name or f"unnamed row {row_id}" for row_id, name in names.items()}
if len(set(labels.values())) == len(labels):
return labels
return {
row_id: f"{name} (row {row_id})" if name else labels[row_id]
for row_id, name in names.items()
}
+37 -6
View File
@@ -1,6 +1,6 @@
import asyncio
import json
from collections.abc import Callable, Iterable
from collections.abc import Awaitable, Callable, Iterable
from dataclasses import dataclass
from functools import cached_property, partial
from typing import TYPE_CHECKING, Any
@@ -343,6 +343,32 @@ class _HeldCallsToolset(WrapperToolset[None]):
return await super().call_tool(name, tool_args, ctx, tool)
@dataclass
class _StopCheckedToolset(WrapperToolset[None]):
"""
Checks the run is still going before each call, so no tool starts after Stop
or a lost lease, which the lease renewal alone notices only seconds later. A
refused call is recorded as not run.
"""
raise_if_stopping: Callable[[], Awaitable[None]]
not_run: Callable[[str], None]
async def call_tool(
self,
name: str,
tool_args: dict[str, Any],
ctx: RunContext[None],
tool: ToolsetTool[None],
) -> Any:
try:
await self.raise_if_stopping()
except asyncio.CancelledError:
self.not_run(ctx.tool_call_id)
raise
return await super().call_tool(name, tool_args, ctx, tool)
@dataclass
class _HeldMCPCallsToolset(WrapperToolset[None]):
"""
@@ -740,11 +766,16 @@ class AgentResponder:
if self._ask_person_tool is not None:
toolsets.append(FunctionToolset([self._ask_person_tool]))
return [
*toolsets,
*(
_HeldMCPCallsToolset(toolset, self._is_held)
for toolset in self._mcp_toolsets
),
_StopCheckedToolset(
toolset, self._journal.raise_if_stopping, self._steps.not_run
)
for toolset in [
*toolsets,
*(
_HeldMCPCallsToolset(toolset, self._is_held)
for toolset in self._mcp_toolsets
),
]
]
def _is_held(self, ctx: RunContext[None]) -> bool:
+97 -3
View File
@@ -3,14 +3,27 @@ from uuid import UUID
from django.contrib.auth import get_user_model
from django.contrib.auth.models import AbstractUser
from django.db import DEFAULT_DB_ALIAS, transaction
from django.db.models import F, QuerySet
from django.db.models import F, Prefetch, QuerySet
from rest_framework.exceptions import ValidationError
from baserow.contrib.integrations.mcp.handler import MCPServerHandler, MCPToolSettings
from baserow.contrib.integrations.mcp.models import (
MCP_SERVER_LOCK_OF,
MCPServerIntegration,
MCPServerTool,
)
from baserow.contrib.integrations.mcp.service import MCPServerService
from baserow.contrib.integrations.mcp.toolset import (
MODEL_TOOL_NAME_PREFIX,
RESERVED_MODEL_TOOL_NAME,
approval_key,
)
from baserow.core.exceptions import PermissionDenied
from baserow.core.handler import CoreHandler
from baserow.core.identities.handler import IdentityHandler
from baserow.core.identities.service import IdentityService
from baserow.core.integrations.operations import UpdateIntegrationOperationType
from baserow.core.models import UserProfile
from baserow.core.operations import (
CreateApplicationsWorkspaceOperationType,
@@ -1104,6 +1117,86 @@ class AgentService:
reply, approved_tools, rejected_tools, always_allowed_tools, run_id
)
def _stop_mcp_tools_asking_first(
self, user: AbstractUser, agent: AgentApplication, approved: dict[str, str]
) -> list[str]:
"""
Stop asking first for the approved calls' MCP tools, while their switched
on server, account and definition are those of the call and nobody has to
review a newer definition. The servers are locked, so none of it changes
meanwhile.
:param user: The user deciding.
:param agent: The Agent, locked.
:param approved: The approval key of each approved call, by tool name.
:return: The tools that stopped asking first.
"""
by_key = {
key: name
for name, key in approved.items()
if key and name.startswith(MODEL_TOOL_NAME_PREFIX)
}
if not by_key:
return []
server_ids = {
int(match.group()[len(MODEL_TOOL_NAME_PREFIX) : -1])
for name in by_key.values()
if (match := RESERVED_MODEL_TOOL_NAME.match(name))
}
# The tools are locked too, as switching one off locks only the tool.
askable = MCPServerTool.objects.select_for_update().filter(
enabled=True, removed=False, ask_first=True, changed_since_review=False
)
servers = (
MCPServerIntegration.objects.select_for_update(of=MCP_SERVER_LOCK_OF)
.filter(
id__in=server_ids,
application_id=agent.id,
trashed=False,
enabled=True,
)
.prefetch_related(Prefetch("tools", askable, to_attr="askable_tools"))
)
stopped = []
for integration in servers:
tools = {
tool.name: by_key[key]
for tool in integration.askable_tools
if (key := approval_key(integration, tool)) in by_key
}
if not tools or not CoreHandler().check_permissions(
user,
UpdateIntegrationOperationType.type,
workspace=agent.workspace,
context=integration,
raise_permission_exceptions=False,
):
continue
stored = MCPServerHandler().update_tools(
integration,
[
MCPToolSettings(
name=tool.name,
ask_first=False,
definition_hash=tool.definition_hash,
)
for tool in integration.askable_tools
if tool.name in tools
],
)
# A tool whose definition changed meanwhile keeps asking.
changed = [
tools[tool.name]
for tool in stored
if tool.name in tools and not tool.ask_first
]
if changed:
# The approver's own page is told too, as for an action.
MCPServerService().notify_updated(None, integration.id)
stopped.extend(changed)
return stopped
def _stop_asking_first(
self,
user: AbstractUser,
@@ -1112,8 +1205,8 @@ class AgentService:
) -> list[str]:
"""
Stop asking first for the tools of the approved calls, telling the Agent's
open pages when its configuration changed. An action only stops asking
while it's still the one whose call was approved.
open pages when its configuration changed. An action or an MCP tool only
stops asking while it's still the one whose call was approved.
:param user: The user deciding, already allowed to update the configuration.
:param agent_id: The id of the Agent.
@@ -1139,4 +1232,5 @@ class AgentService:
# No session edited the action, so the approver's own is told too.
agent_action_updated.send(self, action=updated.action, user=None)
stopped.append(tool.type)
stopped.extend(self._stop_mcp_tools_asking_first(user, agent, approved))
return stopped
@@ -6,6 +6,7 @@ from baserow.contrib.database.views.exceptions import ViewDoesNotExist
from baserow.core.tools import ToolContext
from .database_previews import (
database_name,
database_reference,
named_fields,
readable_names,
@@ -29,18 +30,20 @@ def _without(values: dict[str, Any], key: str) -> dict[str, Any]:
def _field_reference(
field_id: int, names: dict[int, tuple[str, str]]
field_id: int, names: dict[int, tuple[str, str, str]]
) -> dict[str, Any]:
"""
:param field_id: A field the call names.
:param names: The field and table names the identity can see, by field ID.
:return: The field's and its table's names, or its ID as written.
:param names: The field, table and database names the identity can see, by
field ID.
:return: The field's, its table's and its database's names, or its ID as
written.
"""
if field_id not in names:
return {"field_id": field_id}
field_name, table_name = names[field_id]
return {"field": field_name, "table": table_name}
field_name, table_name, database_name = names[field_id]
return {"field": field_name, "table": table_name, "database": database_name}
def _row_reference(row_id: int, names: dict[int, str]) -> dict[str, Any]:
@@ -160,7 +163,12 @@ class GetTableSchemaAgentToolType(DatabaseAgentToolType):
self, ctx: ToolContext, arguments: dict[str, Any], result: Any
) -> dict[str, Any]:
names = [table["name"] for table in result]
return {"table": ", ".join(names)} if names else {}
if not names:
return {}
facts = {"table": ", ".join(names)}
if database := database_name(ctx, [table["id"] for table in result]):
facts["database"] = database
return facts
class ListTableRowsAgentToolType(TableReadAgentToolType):
@@ -346,6 +354,7 @@ class CreateViewFiltersAgentToolType(DatabaseAgentToolType):
{
"view": view.name,
"table": view.table.name,
"database": view.table.database.name,
"filters": name_field_references(group["filters"], names),
}
)
@@ -148,13 +148,13 @@ class MCPServerService:
return self.notify_updated(user, integration_id)
def notify_updated(
self, user: AbstractUser, integration_id: int
self, user: AbstractUser | None, integration_id: int
) -> MCPServerIntegration:
"""
Read the server again, so its prefetched tools are the stored ones, and
tell other editors it changed.
:param user: Who changed it.
:param user: Who changed it, or None to tell their own pages too.
:param integration_id: The integration.
:return: The server.
"""
@@ -291,6 +291,7 @@ class ChatRunSteps:
self._approved_ids = frozenset(approved_ids)
self._resumed_step_ids: set[str] = set()
self._pending: dict[str, deque[str]] = defaultdict(deque)
self._not_run: set[str] = set()
self._call_started = False
def start(self) -> None:
@@ -400,9 +401,35 @@ class ChatRunSteps:
step["presentation_type"] = presentation_type
if invalid:
step["error_code"] = ToolErrorCode.INVALID_INPUT
if tool_call_id in self._not_run:
step.update(
status=ChatRunStepStatus.FAILED, error_code=ToolErrorCode.NOT_RUN
)
self._pending[tool_call_id].append(step["id"])
self._update(step)
def not_run(self, tool_call_id: str) -> None:
"""
Fail a call that was refused before it started, so it isn't shown as a
change that may have completed.
:param tool_call_id: The refused call's id.
"""
self._not_run.add(tool_call_id)
pending = self._pending.get(tool_call_id)
if pending:
step = self._steps[pending.popleft()]
if not pending:
del self._pending[tool_call_id]
self._update(
{
**step,
"status": ChatRunStepStatus.FAILED,
"error_code": ToolErrorCode.NOT_RUN,
}
)
def _resume(self, tool_call_id: str, step_id: str, args_valid: bool | None) -> None:
"""Continue the saved step of a held call the user decided.
@@ -1,12 +1,15 @@
from django.core.mail.backends.locmem import EmailBackend
import pytest
from asgiref.sync import sync_to_async
from fakeredis.aioredis import FakeRedis
from loguru import logger
from pydantic_ai.models.test import TestModel
from baserow.core.ai_provider.models import AIProviderConfig, AIProviderModel
from baserow.core.chat_runs.buffer import set_buffer_redis
from baserow.core.chat_runs.handler import ChatRunHandler
from baserow.core.chat_runs.journal import ChatRunJournal
@pytest.fixture(autouse=True)
@@ -21,6 +24,24 @@ def reply_model(mocker):
return model
@pytest.fixture(autouse=True)
def lease_renewed_in_the_test_transaction(monkeypatch):
"""
A worker renews its lease on a connection of its own, which can't see the run
a test hasn't committed. Renew it on the test's connection instead.
"""
monkeypatch.setattr(
ChatRunJournal,
"_renew_lease",
lambda journal: ChatRunHandler().renew_lease(journal.run.id),
)
monkeypatch.setattr(
"baserow.core.chat_runs.journal.sync_to_async",
lambda function, thread_sensitive=True: sync_to_async(function),
)
@pytest.fixture(autouse=True)
def buffer_redis():
client = FakeRedis(decode_responses=True)
@@ -33,7 +33,9 @@ def accounts(data_fixture):
database=database,
table=table,
secret=secret,
name=name,
acme=model.objects.create(**{f"field_{name.id}": "Acme"}),
other_acme=model.objects.create(**{f"field_{name.id}": "Acme"}),
unnamed=model.objects.create(),
)
@@ -46,16 +48,17 @@ def test_names_are_resolved_as_the_agent_identity(accounts, data_fixture):
name="Secret",
)
# A duplicated database keeps every table's name, so the database is named.
assert table_reference(accounts.ctx, accounts.table.id) == (
accounts.table,
{"table": "Accounts"},
{"database": "Sales", "table": "Accounts"},
)
assert database_reference(accounts.ctx, accounts.database.id) == {
"database": "Sales"
}
assert named_fields(accounts.ctx, [accounts.secret.id, copy.id]) == {
accounts.secret.id: ("Secret", "Accounts"),
copy.id: ("Secret", copy.table.name),
accounts.secret.id: ("Secret", "Accounts", "Sales"),
copy.id: ("Secret", copy.table.name, "Sales"),
}
assert row_names(
accounts.ctx, accounts.table, [accounts.acme.id, accounts.unnamed.id]
@@ -63,6 +66,20 @@ def test_names_are_resolved_as_the_agent_identity(accounts, data_fixture):
accounts.acme.id: "Acme",
accounts.unnamed.id: f"unnamed row {accounts.unnamed.id}",
}
# Rows of the same name are told apart, even from one named like a label.
lookalike = accounts.table.get_model().objects.create(
**{f"field_{accounts.name.id}": f"Acme (row {accounts.other_acme.id})"}
)
assert row_names(
accounts.ctx,
accounts.table,
[accounts.acme.id, accounts.other_acme.id, lookalike.id, accounts.unnamed.id],
) == {
accounts.unnamed.id: f"unnamed row {accounts.unnamed.id}",
accounts.acme.id: f"Acme (row {accounts.acme.id})",
accounts.other_acme.id: f"Acme (row {accounts.other_acme.id})",
lookalike.id: f"Acme (row {accounts.other_acme.id}) (row {lookalike.id})",
}
assert table_reference(accounts.ctx, other.id) == (None, {"table_id": other.id})
assert database_reference(accounts.ctx, other.database_id) == {
"database_id": other.database_id
@@ -80,7 +97,7 @@ def test_missing_hidden_and_trashed_fields_and_rows_are_left_out(
)
assert named_fields(accounts.ctx, [accounts.secret.id, hidden.id, trashed.id]) == {
accounts.secret.id: ("Secret", "Accounts")
accounts.secret.id: ("Secret", "Accounts", "Sales")
}
assert row_names(
accounts.ctx, accounts.table, [accounts.acme.id, accounts.unnamed.id, 999999]
@@ -1057,14 +1057,21 @@ def test_a_stop_during_a_change_waits_for_it_and_saves_it_as_interrupted(
user = data_fixture.create_user()
agent = configured_agent(user=user)
table = allow_tools(data_fixture, agent)
emit = ChatRunJournal.emit
emitted = mocker.spy(ChatRunJournal, "emit")
tool_type = type(agent_tool_type_registry.get("create_rows"))
original = tool_type.function
def emit_and_stop(journal, kind, data=None, flush_now=False):
emit(journal, kind, data, flush_now)
if kind == "step" and data["status"] == "running":
journal.request_stop("cancelled")
@wraps(original)
def stop_and_create(*args, **kwargs):
journal = emitted.call_args.args[0]
journal._loop.call_soon_threadsafe(
journal.request_stop, ChatRunStopReason.CANCELLED
)
while journal.stop_reason is None:
time.sleep(0.01)
return original(*args, **kwargs)
mocker.patch.object(ChatRunJournal, "emit", emit_and_stop)
mocker.patch.object(tool_type, "function", stop_and_create)
async def stream(messages, info):
arguments = {"table_id": table.id, "rows": [{"Name": "Plan"}]}
@@ -1085,6 +1092,38 @@ def test_a_stop_during_a_change_waits_for_it_and_saves_it_as_interrupted(
assert rows == ["Plan"]
@pytest.mark.django_db
def test_no_change_starts_after_stop_is_requested(
data_fixture, configured_agent, mocker
):
user = data_fixture.create_user()
agent = configured_agent(user=user)
table = allow_tools(data_fixture, agent)
respond(mocker, ({0: add_row(table, "call_1"), 1: add_row(table, "call_2")},))
tool_type = type(agent_tool_type_registry.get("create_rows"))
original = tool_type.function
@wraps(original)
def create_and_stop(*args, **kwargs):
# Stop is pressed while the first change runs, as the API requests it.
ChatRunHandler().request_cancel(run_of(created.conversation).id)
return original(*args, **kwargs)
mocker.patch.object(tool_type, "function", create_and_stop)
created = start(user, agent)
run_reply(run_of(created.conversation))
assert reply_state(created.reply.id)[0] == "cancelled"
assert row_names(table) == ["Plan"]
# The refused call is shown as not run, not as a change that may be done.
steps = AgentMessage.objects.get(id=created.reply.id).steps
assert [(step["status"], step.get("error_code")) for step in steps] == [
("done", None),
("failed", "not_run"),
]
@pytest.mark.django_db
def test_the_reply_model_is_the_configured_one(reply_run):
request = AgentService().prepare_reply(reply_run.context["reply_id"])
@@ -1556,7 +1595,11 @@ def test_a_reply_calls_the_allowed_tools_as_the_agent_identity(
"changes_data": True,
"input": {
"requested_count": 1,
"values": {"table": table.name, "rows": [{"Name": "Plan"}]},
"values": {
"database": table.database.name,
"table": table.name,
"rows": [{"Name": "Plan"}],
},
},
"facts": {"count": 1} if valid_facts else {},
}
@@ -1660,7 +1703,11 @@ def test_a_reply_recovers_from_invalid_tool_calls(
assert step["status"] == "done"
assert step["input"] == {
"requested_count": 1,
"values": {"table": table.name, "rows": [{"Name": "Plan"}]},
"values": {
"database": table.database.name,
"table": table.name,
"rows": [{"Name": "Plan"}],
},
}
assert "error_code" not in step
@@ -2139,7 +2186,11 @@ def test_a_held_call_waits_with_its_named_request(ask_first_agent, mocker):
assert step["status"] == "waiting"
assert step["input"] == {
"requested_count": 1,
"values": {"table": table.name, "rows": [{"Name": "Plan"}]},
"values": {
"database": table.database.name,
"table": table.name,
"rows": [{"Name": "Plan"}],
},
}
@@ -1,7 +1,9 @@
from unittest.mock import ANY
from uuid import uuid4
from django.db import connection
from django.test import override_settings
from django.test.utils import CaptureQueriesContext
import pytest
from rest_framework.response import Response
@@ -14,10 +16,16 @@ from baserow.contrib.agent.models import (
AgentReplyStatus,
AgentToolApproval,
)
from baserow.contrib.integrations.mcp.models import (
MCPServerIntegration,
MCPServerTool,
)
from baserow.contrib.integrations.mcp.toolset import approval_key
from baserow.core.action.registries import action_type_registry
from baserow.core.chat_runs.handler import ChatRunHandler
from baserow.core.chat_runs.models import ChatRun, ChatRunStatus
from baserow.core.identities.handler import IdentityHandler
from baserow.core.integrations.signals import integration_updated
from baserow.core.signals import application_updated
from .utils import agent_url, new_conversation
@@ -367,20 +375,89 @@ def test_always_allow_stops_asking_first_only_for_approved_tools_that_ask_first(
assert audited.call_args.args[1]["always_allowed_tools"] == []
configuration_updated.assert_not_called()
audited.reset_mock()
data_fixture.create_mcp_server_integration(application=agent)
response = decide(
api_client,
held_reply,
{"id": created.id, "approved": True},
{"id": updated.id, "approved": True},
{"id": listed.id, "approved": True},
always_allow=True,
)
with CaptureQueriesContext(connection) as queries:
response = decide(
api_client,
held_reply,
{"id": created.id, "approved": True},
{"id": updated.id, "approved": True},
{"id": listed.id, "approved": True},
always_allow=True,
)
assert response.status_code == 200
# No connected app's call was approved, so none is read.
mcp_table = MCPServerIntegration._meta.db_table
assert not any(mcp_table in query["sql"] for query in queries)
assert AgentHandler().get_tool_configuration(agent) == {
"allowed_tools": ["create_rows", "update_rows", "delete_rows"],
"ask_first_tools": ["delete_rows"],
}
assert audited.call_args.args[1]["always_allowed_tools"] == ["create_rows"]
configuration_updated.assert_called_once_with(ANY, application=agent, user=api_user)
@pytest.mark.django_db
def test_always_allow_stops_an_mcp_tool_asking_first_while_it_is_the_approved_one(
api_client, data_fixture, held_reply, mocker
):
agent = held_reply.conversation.agent
integration = data_fixture.create_mcp_server_integration(application=agent)
switched_off = data_fixture.create_mcp_server_integration(
application=agent, enabled=False
)
trashed = data_fixture.create_mcp_server_integration(
application=agent, trashed=True
)
tools = [
MCPServerTool.objects.create(
integration=server,
name=name,
definition_hash="hash",
enabled=enabled,
ask_first=True,
removed=removed,
)
for server, name, enabled, removed in (
(integration, "close_ticket", True, False),
(integration, "reopen_ticket", True, False),
(integration, "delete_ticket", True, True),
(integration, "merge_ticket", False, False),
(switched_off, "close_ticket", True, False),
(trashed, "close_ticket", True, False),
)
]
keys = [approval_key(tool.integration, tool) for tool in tools]
# The reopen call was approved as a definition the tool no longer has.
keys[1] = "old"
for tool, key in zip(tools, keys):
data_fixture.create_agent_tool_approval(
reply=held_reply,
tool_name=f"mcp{tool.integration_id}_{tool.name}",
tool_key=key,
)
close, reopen, *refused = held_reply.approvals.order_by("id")[2:]
audited = mocker.spy(DecideAgentToolApprovalsActionType, "send_action_done_signal")
broadcast = mocker.spy(integration_updated, "send")
response = decide(
api_client,
held_reply,
*({"id": approval.id, "approved": True} for approval in (close, reopen)),
*({"id": approval.id, "approved": True} for approval in refused),
always_allow=True,
)
assert response.status_code == 200
assert [
tool.ask_first
for tool in MCPServerTool.objects.filter(id__in=[t.id for t in tools]).order_by(
"id"
)
] == [False, True, True, True, True, True]
assert audited.call_args.args[1]["always_allowed_tools"] == [close.tool_name]
broadcast.assert_called_once()
assert broadcast.call_args.kwargs["integration"].id == integration.id
assert broadcast.call_args.kwargs["user"] is None
@@ -493,7 +493,7 @@ def test_a_request_that_cannot_be_named_keeps_its_ids_and_is_left_to_the_tool(
"done",
{"values": {"table_id": hidden_id}},
)
assert named.input == {"values": {"table": "Tasks"}}
assert named.input == {"values": {"database": "Work", "table": "Tasks"}}
@pytest.mark.django_db
@@ -510,7 +510,7 @@ def test_a_call_that_fails_after_its_request_was_named_keeps_it(workspace_data):
)
assert result.return_value["error"]["code"] == "invalid_input"
assert result.input == {"values": {"table": "Tasks"}}
assert result.input == {"values": {"database": "Work", "table": "Tasks"}}
@pytest.mark.django_db
@@ -638,7 +638,13 @@ def test_partial_field_creation_counts_only_created_fields(workspace_data):
assert tool_type.get_step_input(arguments) == {"requested_count": 2}
assert (result.metadata, result.input) == (
{"facts": {"count": 1}},
{"values": {"table": "Tasks", "fields": arguments["fields"]}},
{
"values": {
"database": "Work",
"table": "Tasks",
"fields": arguments["fields"],
}
},
)
assert len(result.return_value["errors"]) == 1
@@ -659,8 +665,8 @@ def test_fields_with_the_same_name_stay_separate_entries(workspace_data, data_fi
assert preview == {
"values": {
"fields": [
{"field": "Hours", "table": "Tasks"},
{"field": "Hours", "table": "Notes"},
{"field": "Hours", "table": "Tasks", "database": "Work"},
{"field": "Hours", "table": "Notes", "database": "Work"},
]
}
}
@@ -690,7 +696,10 @@ def test_a_field_that_cannot_be_named_keeps_its_id_and_fails_alone(
assert [error["item"] for error in deleted.return_value["errors"]] == [trashed.id]
assert deleted.input == {
"values": {
"fields": [{"field": "Hours", "table": "Tasks"}, {"field_id": trashed.id}]
"fields": [
{"field": "Hours", "table": "Tasks", "database": "Work"},
{"field_id": trashed.id},
]
}
}
assert updated == {
@@ -823,6 +832,7 @@ def test_view_requests_name_their_fields(workspace_data, data_fixture):
assert preview == {
"values": {
"database": "Work",
"table": "Tasks",
"views": [{"name": "Board", "type": "kanban", "column_field": "Status"}],
}
@@ -847,7 +857,9 @@ def test_views_are_created_when_the_identity_may_not_list_fields(
{"table_id": workspace_data.table.id, "views": [board]},
)
assert result.input == {"values": {"table": "Tasks", "views": [board]}}
assert result.input == {
"values": {"database": "Work", "table": "Tasks", "views": [board]}
}
@pytest.mark.django_db
@@ -866,7 +878,11 @@ def test_row_writes_show_their_values_with_passwords_masked(
)
assert result.input == {
"values": {"table": "Tasks", "rows": [{"Name": "Acme", "Secret": "••••"}]}
"values": {
"database": "Work",
"table": "Tasks",
"rows": [{"Name": "Acme", "Secret": "••••"}],
}
}
@@ -883,7 +899,9 @@ def test_a_failed_row_write_never_stores_a_value_of_a_password_field(
)
assert "error" in result.return_value
assert result.input == {"values": {"table": "Tasks", "rows": [{"secret": "••••"}]}}
assert result.input == {
"values": {"database": "Work", "table": "Tasks", "rows": [{"secret": "••••"}]}
}
assert "hunter2" not in json.dumps(result.input)
@@ -929,6 +947,7 @@ def test_changed_rows_are_named_by_their_primary_value(workspace_data):
assert update == {
"values": {
"database": "Work",
"table": "Tasks",
"rows": [
{"row": "Draft", "values": {"Name": "Done"}},
@@ -937,7 +956,11 @@ def test_changed_rows_are_named_by_their_primary_value(workspace_data):
}
}
assert delete == {
"values": {"table": "Tasks", "rows": ["Draft", f"unnamed row {unnamed.id}"]}
"values": {
"database": "Work",
"table": "Tasks",
"rows": ["Draft", f"unnamed row {unnamed.id}"],
}
}
@@ -954,7 +977,11 @@ def test_a_missing_row_keeps_its_id_and_the_tool_deletes_nothing(workspace_data)
assert result.return_value["error"]["code"] == "not_found"
assert result.input == {
"values": {"table": "Tasks", "rows": ["Draft", {"row_id": 999999}]}
"values": {
"database": "Work",
"table": "Tasks",
"rows": ["Draft", {"row_id": 999999}],
}
}
assert (
workspace_data.table.get_model()
@@ -1091,7 +1118,7 @@ def test_unexpected_tool_errors_do_not_log_private_values(workspace_data, mocker
}
assert (result.metadata, result.input) == (
{"error_code": "failed"},
{"values": {"table": "Tasks"}},
{"values": {"database": "Work", "table": "Tasks"}},
)
output = "".join(str(entry) for entry in logs)
assert "list_table_rows" in output
+7 -2
View File
@@ -19,6 +19,7 @@ The backend emits `step` events and saves the same steps on the assistant messag
"input": {
"requested_count": 2,
"values": {
"database": "Work",
"table": "Tasks",
"rows": [{ "Name": "Acme" }, { "Name": "Beta" }]
}
@@ -91,13 +92,17 @@ failed steps too.
- `input.truncated` marks any of these cuts; the card says the preview is
shortened.
- Each ID is resolved on its own: two fields named "Name" stay two entries.
- A table, field or view is named with its database, as a duplicated database
keeps every name. The tables of a schema read or a creation are too.
- Rows are named by their primary field value, or `unnamed row <id>`, when the
identity may list them.
identity may list them. When two rows of one call read the same, every named
row of the call gets its ID too.
- Field IDs in views and filters become names when the identity may list the
table's fields; others stay as written.
- An integer `linked_table` in `create_fields` the identity can't see stays as
written.
- Reads of one table name only the table, so a held read shows what it reads.
- Reads of one table name only the table and its database, so a held read shows
what it reads.
Tool details start collapsed. Objects with keys are shown as a two-column table.
Nested objects, arrays and other JSON values retain their JSON formatting.
@@ -90,6 +90,7 @@ def test_an_identity_uses_the_row_comment_tools_with_a_workspace_licence(
workspace
)
assert create_request["values"] == {
"database": scenario.database.name,
"table": "Tasks",
"comments": [{"row": "Call", "text": "Ok"}],
}
@@ -102,7 +103,11 @@ def test_an_identity_uses_the_row_comment_tools_with_a_workspace_licence(
}
assert [comment["text"] for comment in found.return_value["comments"]] == ["Ok"]
assert found.metadata == {"facts": {"count": 1}}
assert list_request["values"] == {"table": "Tasks", "row": "Call"}
assert list_request["values"] == {
"database": scenario.database.name,
"table": "Tasks",
"row": "Call",
}
assert listed.metadata == {"facts": {"count": 2}}
search = agent_tool_type_registry.get("search_row_comments")
@@ -52,7 +52,11 @@ def test_tool_calls_recheck_the_identity_role(
}
assert refused.metadata == {"error_code": "permission_denied"}
assert run.emit.await_args.args[0].input == {
"values": {"table": table.name, "rows": [{"Name": "After downgrade"}]}
"values": {
"database": table.database.name,
"table": table.name,
"rows": [{"Name": "After downgrade"}],
}
}
assert list(
table.get_model(attribute_names=True).objects.values_list("name", flat=True)
+19 -6
View File
@@ -39,20 +39,20 @@
"name": "get_table_schema",
"arguments": { "table_ids": [1] },
"input": { "requested_count": 1 },
"facts": { "table": "Tasks" }
"facts": { "table": "Tasks", "database": "Work" }
},
{
"name": "list_table_rows",
"arguments": { "table_id": 1 },
"input": {},
"preview": { "values": { "table": "Tasks" } },
"preview": { "values": { "database": "Work", "table": "Tasks" } },
"facts": { "count": 1 }
},
{
"name": "list_views",
"arguments": { "table_id": 1 },
"input": {},
"preview": { "values": { "table": "Tasks" } },
"preview": { "values": { "database": "Work", "table": "Tasks" } },
"facts": {}
},
{
@@ -83,6 +83,7 @@
"input": { "requested_count": 1 },
"preview": {
"values": {
"database": "Work",
"table": "Tasks",
"fields": [{ "name": "Notes", "type": "text" }]
}
@@ -99,6 +100,7 @@
{
"field": "Hours",
"table": "Tasks",
"database": "Work",
"changes": { "name": "Effort" }
}
]
@@ -111,7 +113,9 @@
"arguments": { "field_ids": [1] },
"input": { "requested_count": 1 },
"preview": {
"values": { "fields": [{ "field": "Hours", "table": "Tasks" }] }
"values": {
"fields": [{ "field": "Hours", "table": "Tasks", "database": "Work" }]
}
},
"facts": { "count": 1 }
},
@@ -124,6 +128,7 @@
"input": { "requested_count": 1 },
"preview": {
"values": {
"database": "Work",
"table": "Tasks",
"views": [{ "name": "Board", "type": "grid" }]
}
@@ -154,6 +159,7 @@
{
"view": "Grid",
"table": "Tasks",
"database": "Work",
"filters": [
{
"field": "Hours",
@@ -173,7 +179,11 @@
"arguments": { "table_id": 1, "rows": [{ "Name": "Plan" }] },
"input": { "requested_count": 1 },
"preview": {
"values": { "table": "Tasks", "rows": [{ "Name": "Plan" }] }
"values": {
"database": "Work",
"table": "Tasks",
"rows": [{ "Name": "Plan" }]
}
},
"facts": { "count": 1 }
},
@@ -183,6 +193,7 @@
"input": { "requested_count": 1 },
"preview": {
"values": {
"database": "Work",
"table": "Tasks",
"rows": [{ "row": "Draft", "values": { "Name": "Done" } }]
}
@@ -193,7 +204,9 @@
"name": "delete_rows",
"arguments": { "table_id": 1, "row_ids": [1] },
"input": { "requested_count": 1 },
"preview": { "values": { "table": "Tasks", "rows": ["Draft"] } },
"preview": {
"values": { "database": "Work", "table": "Tasks", "rows": ["Draft"] }
},
"facts": { "count": 1 }
}
]
@@ -371,6 +371,7 @@
"toolDeleteRowsRequestedCountTable": "Delete {count} row from {table} | Delete {count} rows from {table}",
"toolListTableRowsRequestedTable": "Read rows from {table}",
"toolListViewsRequestedTable": "List views of {table}",
"tableInDatabase": "{table} ({database})",
"approvalRequest": "{name} asks for your approval",
"approvalRequestReadOnly": "{name} asks for approval",
"approvalReviewed": "Reviewed",
@@ -8,9 +8,20 @@ import {
const countIsKnown = (count) => Number.isSafeInteger(count) && count >= 0
const trimmedName = (name) => (typeof name === 'string' ? name.trim() : '')
/**
* A table's name, with its database when one is known, as a duplicated
* database keeps every table's name.
*/
const tableInDatabase = (table, database, t) =>
table && database ? t('agent.tableInDatabase', { table, database }) : table
/** The table a call's request names, or '' when it names none. */
const requestedTable = (input) =>
typeof input?.values?.table === 'string' ? input.values.table.trim() : ''
const requestedTable = (input, t) =>
tableInDatabase(
trimmedName(input?.values?.table),
trimmedName(input?.values?.database),
t
)
/** Database presenters share count/table formatting; Core knows neither field. */
export class DatabaseToolPresentationType extends ToolPresentationType {
@@ -41,7 +52,7 @@ export class DatabaseToolPresentationType extends ToolPresentationType {
/** Titled by what the call asks to do: counted changes by count, reads by table. */
getRequestedActivity({ input }, t) {
const { counted, table: titledByTable } = this.constructor.definition
const table = titledByTable ? requestedTable(input) : ''
const table = titledByTable ? requestedTable(input, t) : ''
if (counted !== true) {
return table
? t(`${this.labelKey}RequestedTable`, { table })
@@ -72,9 +83,14 @@ export class DatabaseToolPresentationType extends ToolPresentationType {
const hasCount =
(counted === true || counted === status) && countIsKnown(count)
// Facts name tables that were created or read; other calls name the table asked for.
const tableName =
(typeof facts.table === 'string' && facts.table.trim()) ||
requestedTable(input)
const factTable = trimmedName(facts.table)
const tableName = factTable
? tableInDatabase(
factTable,
trimmedName(facts.database) || trimmedName(input?.values?.database),
t
)
: requestedTable(input, t)
const hasTable = status === STEP_STATUS.DONE && table && tableName
const key = `${this.labelKey}${status === STEP_STATUS.RUNNING ? 'Running' : 'Done'}${hasCount ? 'Count' : ''}${hasTable ? 'Table' : ''}`
return t(
@@ -471,6 +471,41 @@ describe('Agent tool presentations', () => {
})
})
test('a request names the database of its table', () => {
const data = step('delete_rows', 'waiting', {
input: {
requested_count: 1,
values: { database: 'Sales 2', table: 'Accounts', rows: ['Acme'] },
},
})
expect(toolActivity(data, registry, t).title).toBe(
'Delete 1 row from Accounts (Sales 2)'
)
})
test('done reads and creations name the database of their tables', () => {
expect(
toolActivity(
step('get_table_schema', 'done', {
facts: { table: 'Accounts', database: 'Sales 2' },
}),
registry,
t
).title
).toContain('Accounts (Sales 2)')
expect(
toolActivity(
step('create_tables', 'done', {
input: { values: { database: 'Sales 2', tables: [] } },
facts: { count: 1, table: 'Projects' },
}),
registry,
t
).title
).toBe('Created 1 table: Projects (Sales 2)')
})
test('a cut request keeps the shortened-preview flag', () => {
const data = step('create_rows', 'done', {
input: {