Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

fix(teamhub): run an Agent's Discord read at once only inside its server

shoudi zheng3ae7dada9447
diff --git a/apps/teamhub/internal/agentconnectedapps/access.go b/apps/teamhub/internal/agentconnectedapps/access.go
index 13c6c56a..ee85c57e 100644
--- a/apps/teamhub/internal/agentconnectedapps/access.go
+++ b/apps/teamhub/internal/agentconnectedapps/access.go
@@ -68,7 +68,8 @@ func onlyQueries(document any) bool {
// readTools are the provider reads the wrapped connector commands make,
// including the draft reads TeamHub makes to build a send-draft card, plus the
-// Discord reads of the connected guild, its channels, threads, and messages, the
+// Discord reads of the connected guild, its channels, threads, and messages
+// (which run at once only inside the connected guild; see discordReadInScope), the
// Slack reads Agents make through the generic execute to find direct messages
// and the people in them, and the Linear reads, which have no wrapped command.
// A read the generic execute names outside this list is held like a write.
diff --git a/apps/teamhub/internal/agentconnectedapps/confirmation.go b/apps/teamhub/internal/agentconnectedapps/confirmation.go
index 1597b3d1..3fd4f13c 100644
--- a/apps/teamhub/internal/agentconnectedapps/confirmation.go
+++ b/apps/teamhub/internal/agentconnectedapps/confirmation.go
@@ -200,6 +200,11 @@ func (s *Service) readTool(ctx context.Context, connection externalsource.AgentT
if !execution.Successful || !ok {
return nil, &Error{Code: "tool_execution_failed", Message: "The connected application did not return the draft"}
}
+ return toolData(data), nil
+}
+
+// toolData returns a read's own result object.
+func toolData(data map[string]any) map[string]any {
// Some tools wrap their result in their own execution envelope.
if inner, ok := data["data"].(map[string]any); ok {
if _, wrapped := data["successful"]; wrapped {
@@ -209,7 +214,7 @@ func (s *Service) readTool(ctx context.Context, connection externalsource.AgentT
if inner, ok := data["response_data"].(map[string]any); ok {
data = inner
}
- return data, nil
+ return data
}
func digestOf(value any) string {
diff --git a/apps/teamhub/internal/agentconnectedapps/discord_scope.go b/apps/teamhub/internal/agentconnectedapps/discord_scope.go
new file mode 100644
index 00000000..9b7dda74
--- /dev/null
+++ b/apps/teamhub/internal/agentconnectedapps/discord_scope.go
@@ -0,0 +1,89 @@
+package agentconnectedapps
+
+import (
+ "context"
+ "net/http"
+
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/composio"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/externalsource"
+)
+
+// discordChannelLookupVersion is the DISCORDBOT_GET_CHANNEL version TeamHub
+// reads a channel's server with. It is pinned here, not taken from the
+// Agent's call, so the scope check reads the response shape it was written
+// against whatever version the Agent pins.
+const discordChannelLookupVersion = "20261116_00"
+
+// discordScope says what each Discord read names: nothing beyond the
+// connected server, a server by guild_id, or a channel or thread by
+// channel_id. The managed Discord bot is one application shared by every
+// connection, so the provider alone does not keep a read inside the server
+// this connection was installed in.
+type discordScope int
+
+const (
+ discordConnectedGuild discordScope = iota + 1
+ discordGuildArgument
+ discordChannelArgument
+)
+
+var discordReadScopes = map[string]discordScope{
+ "DISCORDBOT_GET_CONNECTED_GUILD": discordConnectedGuild,
+ "DISCORDBOT_GET_GUILD": discordGuildArgument,
+ "DISCORDBOT_LIST_GUILD_CHANNELS": discordGuildArgument,
+ "DISCORDBOT_GET_ACTIVE_GUILD_THREADS": discordGuildArgument,
+ "DISCORDBOT_GET_CHANNEL": discordChannelArgument,
+ "DISCORDBOT_LIST_PUBLIC_ARCHIVED_THREADS": discordChannelArgument,
+ "DISCORDBOT_LIST_MESSAGES": discordChannelArgument,
+ "DISCORDBOT_GET_MESSAGE": discordChannelArgument,
+ "DISCORDBOT_LIST_PINNED_MESSAGES": discordChannelArgument,
+}
+
+// discordReadInScope reports whether a read may run at once. Every read
+// outside Discord may. A Discord read may only when it provably stays in the
+// connection's server (RemoteTeamID); anything TeamHub cannot prove, including
+// a lookup the provider refused, is held for the sponsor like a write. A
+// lookup that failed transiently returns its error, so the read neither runs
+// nor waits on a card.
+func (s *Service) discordReadInScope(ctx context.Context, connection externalsource.AgentToolConnection, slug string, arguments map[string]any) (bool, error) {
+ scope, discord := discordReadScopes[slug]
+ if !discord {
+ return true, nil
+ }
+ switch scope {
+ case discordConnectedGuild:
+ return true, nil
+ case discordGuildArgument:
+ guildID, _ := arguments["guild_id"].(string)
+ return connection.RemoteTeamID != "" && guildID == connection.RemoteTeamID, nil
+ case discordChannelArgument:
+ channelID, _ := arguments["channel_id"].(string)
+ if channelID == "" || connection.RemoteTeamID == "" {
+ return false, nil
+ }
+ execution, err := s.provider.ExecuteTool(ctx, connection.UpstreamConnectionID, connection.UserID,
+ "DISCORDBOT_GET_CHANNEL", discordChannelLookupVersion, map[string]any{"channel_id": channelID})
+ if err != nil {
+ if refusedLookup(err) {
+ return false, nil
+ }
+ return false, mapToolError(&providerOperationError{phase: "discord_channel_lookup", err: err}, "execute")
+ }
+ data, ok := execution.Data.(map[string]any)
+ if !execution.Successful || !ok {
+ return false, nil
+ }
+ guildID, _ := toolData(data)["guild_id"].(string)
+ return guildID == connection.RemoteTeamID, nil
+ default:
+ return false, nil
+ }
+}
+
+// refusedLookup reports a client error that retrying will not change, such
+// as a channel the bot cannot see; timeouts and rate limits are transient.
+func refusedLookup(err error) bool {
+ status, ok := composio.ErrorStatus(err)
+ return ok && status >= 400 && status < 500 &&
+ status != http.StatusRequestTimeout && status != http.StatusTooManyRequests
+}
diff --git a/apps/teamhub/internal/agentconnectedapps/discord_scope_test.go b/apps/teamhub/internal/agentconnectedapps/discord_scope_test.go
new file mode 100644
index 00000000..90547bb2
--- /dev/null
+++ b/apps/teamhub/internal/agentconnectedapps/discord_scope_test.go
@@ -0,0 +1,168 @@
+package agentconnectedapps
+
+import (
+ "context"
+ "errors"
+ "net/http"
+ "reflect"
+ "strings"
+ "testing"
+
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/composio"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/externalsource"
+)
+
+type discordCall struct {
+ slug, version string
+ arguments map[string]any
+}
+
+// discordProvider serves one Discord tool and answers TeamHub's channel
+// lookup with lookup and lookupErr.
+type discordProvider struct {
+ fakeToolProvider
+ tool composio.Tool
+ lookup composio.ToolExecution
+ lookupErr error
+ calls []discordCall
+}
+
+func (provider *discordProvider) GetTool(context.Context, string, string) (composio.Tool, error) {
+ return provider.tool, nil
+}
+
+func (provider *discordProvider) ExecuteTool(_ context.Context, _, _, slug, version string, arguments map[string]any) (composio.ToolExecution, error) {
+ provider.calls = append(provider.calls, discordCall{slug: slug, version: version, arguments: arguments})
+ if slug == "DISCORDBOT_GET_CHANNEL" && version == discordChannelLookupVersion {
+ return provider.lookup, provider.lookupErr
+ }
+ return composio.ToolExecution{Successful: true, Data: map[string]any{"ok": true}}, nil
+}
+
+// ran reports whether the Agent's own call reached the provider.
+func (provider *discordProvider) ran() bool {
+ for _, call := range provider.calls {
+ if call.version == provider.tool.Version {
+ return true
+ }
+ }
+ return false
+}
+
+func executeDiscord(t *testing.T, provider *discordProvider, slug, remoteTeamID string, arguments map[string]any) (Result, error) {
+ t.Helper()
+ provider.tool = tool(slug, "discordbot")
+ connection := externalsource.AgentToolConnection{
+ ID: "connection-1", AppKey: "discordbot", ToolkitSlug: "discordbot", DisplayName: "Discord",
+ UpstreamConnectionID: "ca-1", UserID: "owner", RemoteTeamID: remoteTeamID,
+ }
+ return (&Service{provider: provider}).execute(t.Context(), ExecuteInput{
+ ConnectionID: connection.ID, ToolSlug: slug, ToolVersion: provider.tool.Version, Arguments: arguments,
+ }, func(context.Context) (externalsource.AgentToolConnection, error) { return connection, nil })
+}
+
+func channelIn(guildID string) composio.ToolExecution {
+ return composio.ToolExecution{Successful: true, Data: map[string]any{"id": "c1", "guild_id": guildID}}
+}
+
+func TestDiscordReadsOfEveryKindAreScoped(t *testing.T) {
+ for slug := range readTools {
+ if strings.HasPrefix(slug, "DISCORDBOT_") && discordReadScopes[slug] == 0 {
+ t.Errorf("%s runs at once without a guild scope check", slug)
+ }
+ }
+ for slug := range discordReadScopes {
+ if !readTools[slug] {
+ t.Errorf("%s is scoped but not a read", slug)
+ }
+ }
+}
+
+func TestDiscordConnectedGuildReadRunsWithoutLookup(t *testing.T) {
+ provider := &discordProvider{}
+ result, err := executeDiscord(t, provider, "DISCORDBOT_GET_CONNECTED_GUILD", "g1", map[string]any{})
+ if err != nil || result.Confirmation != nil || len(provider.calls) != 1 || !provider.ran() {
+ t.Fatalf("result=%+v err=%v calls=%+v", result, err, provider.calls)
+ }
+}
+
+func TestDiscordGuildReadRunsOnlyInTheConnectedGuild(t *testing.T) {
+ provider := &discordProvider{}
+ result, err := executeDiscord(t, provider, "DISCORDBOT_LIST_GUILD_CHANNELS", "g1", map[string]any{"guild_id": "g1"})
+ if err != nil || result.Confirmation != nil || len(provider.calls) != 1 || !provider.ran() {
+ t.Fatalf("matching guild: result=%+v err=%v calls=%+v", result, err, provider.calls)
+ }
+ for name, test := range map[string]struct {
+ remote string
+ arguments map[string]any
+ }{
+ "another guild": {"g1", map[string]any{"guild_id": "g2"}},
+ "non-string guild": {"g1", map[string]any{"guild_id": 1}},
+ "missing guild": {"g1", map[string]any{}},
+ "no verified guild": {"", map[string]any{"guild_id": ""}},
+ } {
+ provider := &discordProvider{}
+ result, err := executeDiscord(t, provider, "DISCORDBOT_GET_GUILD", test.remote, test.arguments)
+ if err != nil || result.Confirmation == nil || len(provider.calls) != 0 {
+ t.Fatalf("%s: result=%+v err=%v calls=%+v", name, result, err, provider.calls)
+ }
+ }
+}
+
+func TestDiscordChannelReadLooksUpTheChannelsGuild(t *testing.T) {
+ provider := &discordProvider{lookup: composio.ToolExecution{Successful: true, Data: map[string]any{
+ "successful": true, "data": map[string]any{"guild_id": "g1"},
+ }}}
+ result, err := executeDiscord(t, provider, "DISCORDBOT_LIST_MESSAGES", "g1", map[string]any{"channel_id": "c1", "limit": 5})
+ if err != nil || result.Confirmation != nil || !provider.ran() || len(provider.calls) != 2 {
+ t.Fatalf("result=%+v err=%v calls=%+v", result, err, provider.calls)
+ }
+ lookup := provider.calls[0]
+ if lookup.slug != "DISCORDBOT_GET_CHANNEL" || lookup.version != discordChannelLookupVersion ||
+ !reflect.DeepEqual(lookup.arguments, map[string]any{"channel_id": "c1"}) {
+ t.Fatalf("lookup=%+v", lookup)
+ }
+}
+
+func TestDiscordChannelReadOutsideTheGuildIsHeld(t *testing.T) {
+ for name, provider := range map[string]*discordProvider{
+ "another guild": {lookup: channelIn("g2")},
+ "no guild": {lookup: composio.ToolExecution{Successful: true, Data: map[string]any{"id": "c1"}}},
+ "unsuccessful": {lookup: composio.ToolExecution{Successful: false}},
+ "forbidden": {lookupErr: composio.RemoteStatusError("execute tool", http.StatusForbidden)},
+ "not found": {lookupErr: composio.RemoteStatusError("execute tool", http.StatusNotFound)},
+ "bad argument": {lookup: channelIn("g1")},
+ "no remote guild": {lookup: channelIn("")},
+ } {
+ arguments, remote := map[string]any{"channel_id": "c1"}, "g1"
+ switch name {
+ case "bad argument":
+ arguments = map[string]any{"channel_id": 7}
+ case "no remote guild":
+ remote = ""
+ }
+ result, err := executeDiscord(t, provider, "DISCORDBOT_GET_MESSAGE", remote, arguments)
+ if err != nil || result.Confirmation == nil || provider.ran() {
+ t.Fatalf("%s: result=%+v err=%v calls=%+v", name, result, err, provider.calls)
+ }
+ }
+}
+
+func TestDiscordChannelLookupFailureIsReturned(t *testing.T) {
+ for name, test := range map[string]struct {
+ err error
+ code string
+ }{
+ "server error": {composio.RemoteStatusError("execute tool", http.StatusBadGateway), "provider_unavailable"},
+ "rate limited": {composio.RemoteStatusError("execute tool", http.StatusTooManyRequests), "provider_rate_limited"},
+ "timeout": {context.DeadlineExceeded, "provider_unavailable"},
+ } {
+ provider := &discordProvider{lookupErr: test.err}
+ result, err := executeDiscord(t, provider, "DISCORDBOT_GET_CHANNEL", "g1", map[string]any{"channel_id": "c1"})
+ var domain *Error
+ if !errors.As(err, &domain) || domain.Code != test.code || !domain.Retryable ||
+ result.Confirmation != nil || provider.ran() {
+ t.Fatalf("%s: result=%+v err=%v calls=%+v", name, result, err, provider.calls)
+ }
+ }
+}
diff --git a/apps/teamhub/internal/agentconnectedapps/service.go b/apps/teamhub/internal/agentconnectedapps/service.go
index 6df0e74a..fc121023 100644
--- a/apps/teamhub/internal/agentconnectedapps/service.go
+++ b/apps/teamhub/internal/agentconnectedapps/service.go
@@ -306,7 +306,17 @@ func (s *Service) execute(ctx context.Context, input ExecuteInput, authorize fun
if _, err := s.pinnedTool(ctx, connection, input.ToolSlug, input.ToolVersion, "execute"); err != nil {
return Result{}, err
}
- if accessOf(input.ToolSlug, input.Arguments) == accessConfirm {
+ access := accessOf(input.ToolSlug, input.Arguments)
+ if access == accessRead {
+ inScope, err := s.discordReadInScope(ctx, connection, input.ToolSlug, input.Arguments)
+ if err != nil {
+ return Result{}, err
+ }
+ if !inScope {
+ access = accessConfirm
+ }
+ }
+ if access == accessConfirm {
return s.prepareConfirmation(ctx, connection, confirmationAction{
ToolSlug: input.ToolSlug, ToolVersion: input.ToolVersion, Arguments: input.Arguments,
})
diff --git a/apps/teamhub/internal/externalsource/agent_tools.go b/apps/teamhub/internal/externalsource/agent_tools.go
index 47e43f41..1c328378 100644
--- a/apps/teamhub/internal/externalsource/agent_tools.go
+++ b/apps/teamhub/internal/externalsource/agent_tools.go
@@ -18,7 +18,10 @@ type AgentToolConnection struct {
IdentityLabel string
ToolkitSlug string
UpstreamConnectionID string
- Revision int64
+ // RemoteTeamID is the workspace the connection was verified in, such as
+ // a Discord bot's server; empty when the app has none.
+ RemoteTeamID string
+ Revision int64
}
func (s *Service) ListGrantedAgentToolConnectionsInTx(
@@ -32,7 +35,7 @@ func (s *Service) ListGrantedAgentToolConnectionsInTx(
rows, err := tx.Query(ctx, `
SELECT connection.account_id,connection.id,connection.provider,
coalesce(connection.identity_label,''),coalesce(connection.toolkit_slug,''),
- connection.upstream_connection_id,connection.revision
+ connection.upstream_connection_id,coalesce(connection.remote_team_id,''),connection.revision
FROM external_connection_agent_grants delegation
JOIN external_connections connection ON connection.id=delegation.connection_id
JOIN agent_registrations registration
@@ -63,7 +66,7 @@ func (s *Service) ListGrantedAgentToolConnectionsInTx(
var connection AgentToolConnection
if err := rows.Scan(
&connection.AccountID, &connection.ID, &connection.AppKey, &connection.IdentityLabel,
- &connection.ToolkitSlug, &connection.UpstreamConnectionID, &connection.Revision,
+ &connection.ToolkitSlug, &connection.UpstreamConnectionID, &connection.RemoteTeamID, &connection.Revision,
); err != nil {
return nil, err
}
@@ -102,12 +105,12 @@ func (s *Service) LockGrantedAgentToolConnectionInTx(
var status string
if err := tx.QueryRow(ctx, `
SELECT account_id,id,provider,coalesce(identity_label,''),coalesce(toolkit_slug,''),
- upstream_connection_id,revision,status
+ upstream_connection_id,coalesce(remote_team_id,''),revision,status
FROM external_connections
WHERE id=$1
FOR SHARE`, connectionID).Scan(
&connection.AccountID, &connection.ID, &connection.AppKey, &connection.IdentityLabel,
- &connection.ToolkitSlug, &connection.UpstreamConnectionID, &connection.Revision, &status,
+ &connection.ToolkitSlug, &connection.UpstreamConnectionID, &connection.RemoteTeamID, &connection.Revision, &status,
); errors.Is(err, pgx.ErrNoRows) {
return AgentToolConnection{}, ErrNotFound
} else if err != nil {
diff --git a/apps/teamhub/tests/integration/connected_apps_agent_grants_test.go b/apps/teamhub/tests/integration/connected_apps_agent_grants_test.go
index f8db219b..d443df6c 100644
--- a/apps/teamhub/tests/integration/connected_apps_agent_grants_test.go
+++ b/apps/teamhub/tests/integration/connected_apps_agent_grants_test.go
@@ -184,6 +184,9 @@ func TestConnectedAppsAgentGrantIsExplicitAccountScopedAndRevokedOnDisconnect(t
t.Fatalf("grant attempt=%d result=%+v", attempt+1, granted)
}
}
+ if _, err := pool.Exec(t.Context(), `UPDATE external_connections SET remote_team_id='team-1' WHERE id=$1`, connectionID); err != nil {
+ t.Fatal(err)
+ }
toolService := composioFake.externalSources(t, pool, nil)
toolTx, err := pool.Begin(t.Context())
if err != nil {
@@ -195,13 +198,14 @@ func TestConnectedAppsAgentGrantIsExplicitAccountScopedAndRevokedOnDisconnect(t
if err != nil {
t.Fatal(err)
}
- if len(connections) != 1 || connections[0].ID != connectionID || connections[0].AccountID != "account_alice" {
+ if len(connections) != 1 || connections[0].ID != connectionID || connections[0].AccountID != "account_alice" ||
+ connections[0].RemoteTeamID != "team-1" {
t.Fatalf("granted MCP connections=%+v", connections)
}
locked, err := toolService.LockGrantedAgentToolConnectionInTx(
t.Context(), toolTx, agentActorID, acmeTenant, connectionID,
)
- if err != nil || locked.ID != connectionID {
+ if err != nil || locked != connections[0] {
t.Fatalf("locked MCP connection=%+v err=%v", locked, err)
}
if err := toolTx.Rollback(t.Context()); err != nil {