Skip to content

Commit 60d2039

Browse files
author
ben
authored
feat(workbot): any connection as an agent source, with pinned tool approvals (#6733)
* feat(workbot): any connection as an agent source, with pinned tool approvals Brings #6717 to dev (it merged into #6692's branch after #6692 had merged). Admin approvals of MCP tools are now pinned to each tool's definition (name, description, input schema, hints) and require the provider's read-only marking, so a provider can't turn an approved tool into a write under the same name. * fix(workbot): declare the source tools route for audit, and update the agent sources proof to My bot's redesigned page * test(workbot): tools without a read-only marking are blocked; pick tools by test id in the agent sources proof
1 parent d3324d0 commit 60d2039

17 files changed

Lines changed: 1084 additions & 200 deletions

‎ee/apps/den-api/src/audit/routes/org.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,7 @@ export const orgAuditRoutes: readonly AuditRouteDeclaration[] = [
126126
member("GET", "/v1/org/workbot-settings", "tenant_read", "workbot.settings.read", "organization.settings", "organization", null),
127127
member("GET", "/v1/org/workbot-settings/proactive", "tenant_read", "workbot.agent.settings.read", "organization.settings", "organization", null, { notes: "Members' agents: organization policy, the current Your agent template version and Slack connection names that can deliver; no member content." }),
128128
member("GET", "/v1/org/workbot-settings/proactive/health", "tenant_read", "workbot.agent.health.read", "organization.settings", "organization", null, { notes: "Seven days of agent_check counters per responsibility and mute counts from agent_instance overrides; counts only, no member identities or content." }),
129+
member("GET", "/v1/org/workbot-settings/proactive/connections/:connectionId/tools", "tenant_read", "workbot.agent.source_tools.read", "organization.settings", "organization", null, { notes: "Upstream tools/list of one MCP connection with the caller's credential (conditional OAuth token refresh write), for choosing which read-only tools members' agents may call; no tool is called. Names, descriptions, hints and blocked/changed flags only; approval pins stay server-side." }),
129130
member("PUT", "/v1/org/workbot-settings/proactive", "tenant_change", "workbot.agent.settings.update", "organization.settings", "organization", null, { notes: "Sets organization metadata workbot.proactive (agents on/off, working hours, daily limit, members' starting choice, default destination). A responsibilities or instructions change inserts a config_object_version of the organization's Your agent config object (type agent). Members' own choices are kept." }),
130131
member("GET", "/v1/org/automation-settings", "tenant_read", "automation.settings.read", "organization.settings", "organization", null),
131132
member("PUT", "/v1/org/automation-settings", "tenant_change", "automation.settings.update", "organization.settings", "organization", null, { notes: "Sets organization metadata automations.desktop / automations.cloud. Turning a kind off stops creation and skips its scheduled runs; existing Automations are kept." }),
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import { eq } from "@openwork-ee/den-db/drizzle"
2+
import { OrganizationTable } from "@openwork-ee/den-db/schema"
3+
import { normalizeDenTypeId } from "@openwork-ee/utils/typeid"
4+
import { readWorkbotProactiveSettings, type AgentSourcesPolicy } from "@openwork/types/den/workbot-proactive"
5+
import { db } from "../db.js"
6+
import type { AgentReadAllowlist } from "./agent-read-sources.js"
7+
8+
/**
9+
* The tools an admin approved for a member's agent, added to its token's allowlist when a call is made, each with the
10+
* definition it was approved as. Approvals live in the organization's policy (Manage › Workbot › What agents read),
11+
* not on the token: a token stays small whatever the admin approved, and a removed approval holds from the next call.
12+
* Only connections already on the token count, and an approved tool without a pinned definition counts for nothing.
13+
*/
14+
export function withApprovedTools(allowlist: AgentReadAllowlist, sources: Pick<AgentSourcesPolicy, "readTools" | "readToolPins">): AgentReadAllowlist {
15+
const approvedTools = new Map<string, ReadonlyMap<string, string>>()
16+
for (const [connectionId, tools] of Object.entries(sources.readTools ?? {})) {
17+
if (!allowlist.connectionIds.has(connectionId)) continue
18+
const pins = sources.readToolPins?.[connectionId] ?? {}
19+
const pinned = new Map(tools.flatMap((name) => (pins[name] ? [[name, pins[name]] as const] : [])))
20+
if (pinned.size) approvedTools.set(connectionId, pinned)
21+
}
22+
return { ...allowlist, approvedTools }
23+
}
24+
25+
export async function withAgentApprovedTools(allowlist: AgentReadAllowlist, organizationId: string): Promise<AgentReadAllowlist> {
26+
const [organization] = await db
27+
.select({ metadata: OrganizationTable.metadata })
28+
.from(OrganizationTable)
29+
.where(eq(OrganizationTable.id, normalizeDenTypeId("organization", organizationId)))
30+
.limit(1)
31+
return withApprovedTools(allowlist, readWorkbotProactiveSettings(organization?.metadata).sources)
32+
}

‎ee/apps/den-api/src/mcp/agent-read-sources.ts‎

Lines changed: 61 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { AGENT_CORE_SOURCES, type AgentCoreSource } from "@openwork/types/den/workbot-proactive"
2+
import { externalMcpToolSchemaDigest } from "./external-mcp-tool-arguments.js"
23

34
/**
45
* What a member's background agent ("Your agent") may read through Connect. Its turn runs with a read-scoped token
@@ -7,8 +8,13 @@ import { AGENT_CORE_SOURCES, type AgentCoreSource } from "@openwork/types/den/wo
78
*
89
* - A plain `mcp:read` token never calls a connection's own tools: provider hints can't prove a tool won't change
910
* anything. An agent token may, but only on its connections and only tools we reviewed as reads, per service
10-
* (`REVIEWED_READ_TOOLS`). A service without a reviewed list can't be a source at all; its provider's hints and tool
11-
* names never make a tool callable.
11+
* (`REVIEWED_READ_TOOLS`), or, for a service without a reviewed list, the tools an admin approved for that
12+
* connection (`readTools` in the organization's policy, read when the call is made; agent-approved-tools.ts). An
13+
* approval is pinned to the tool's exact definition when the admin saves it (`readToolPins`): if the provider changes
14+
* the tool (its description, inputs or hints) while keeping its name, the approval no longer matches and the agent
15+
* can't call it until an admin approves it again. Only tools the provider marks read-only (and not destructive) can
16+
* be approved or called this way. A tool whose name says it writes is never callable, approved or not; provider
17+
* hints alone never make a tool callable.
1218
* - Native Google Workspace and Microsoft 365 reads are limited to the core sources that are on: calendar events,
1319
* mail, and Teams chats. Nothing else (files, drafts, sites) and never a non-GET.
1420
*
@@ -28,6 +34,12 @@ export type AgentReadAllowlist = {
2834
connectionIds: ReadonlySet<string>
2935
/** `<kind>:<connectionId>`: which core source each native connection may be read for. */
3036
pairs: ReadonlySet<string>
37+
/**
38+
* Tools an admin approved per connection without a reviewed read list, each with the definition it was approved as
39+
* (`agentToolDigest`). Never carried on the token: added when the call is made from the organization's current
40+
* policy, so a removed approval takes effect at once.
41+
*/
42+
approvedTools?: ReadonlyMap<string, ReadonlyMap<string, string>>
3143
}
3244

3345
function isCoreSource(value: string): value is AgentCoreSource {
@@ -121,17 +133,55 @@ function hostOf(url: string): string | null {
121133
}
122134
}
123135

124-
/** Whether agents can read through a connection at all: its service has a reviewed list of read tools. */
136+
/** Whether a connection's service has a reviewed list of read tools (no admin approval needed). */
125137
export function agentReadableConnection(connectionUrl: string): boolean {
126138
const host = hostOf(connectionUrl)
127139
return host !== null && REVIEWED_READ_TOOLS[host] !== undefined
128140
}
129141

130-
/** Whether a connection's tool is one we reviewed as a read. Provider hints are never enough. */
131-
export function agentReadTool(connectionUrl: string, tool: { name: string }): boolean {
132-
if (WRITE_WORDS.test(tool.name)) return false
142+
/** A tool whose name says it writes (send, create, delete, update…): never callable by an agent, never approvable. */
143+
export function agentToolBlocked(toolName: string): boolean {
144+
return WRITE_WORDS.test(toolName)
145+
}
146+
147+
/** An MCP tool as its provider lists it: what an approval is pinned to. */
148+
export type AgentToolDefinition = {
149+
name: string
150+
description?: string
151+
inputSchema?: Record<string, unknown>
152+
annotations?: { title?: string; readOnlyHint?: boolean; destructiveHint?: boolean; idempotentHint?: boolean; openWorldHint?: boolean }
153+
}
154+
155+
/** The provider marks the tool read-only and not destructive. Required, never sufficient, for an approved tool. */
156+
export function agentToolMarkedReadOnly(tool: Pick<AgentToolDefinition, "annotations">): boolean {
157+
return tool.annotations?.readOnlyHint === true && tool.annotations.destructiveHint !== true
158+
}
159+
160+
/**
161+
* The exact definition an admin approved: name, description, input schema and hints. A provider that changes any of
162+
* them under the same name no longer matches, so the approval stops applying.
163+
*/
164+
export function agentToolDigest(tool: AgentToolDefinition): string {
165+
const annotations = tool.annotations
166+
? Object.fromEntries((["title", "readOnlyHint", "destructiveHint", "idempotentHint", "openWorldHint"] as const)
167+
.flatMap((key) => (tool.annotations?.[key] === undefined ? [] : [[key, tool.annotations[key]]])))
168+
: null
169+
return externalMcpToolSchemaDigest({ name: tool.name, description: tool.description ?? null, inputSchema: tool.inputSchema ?? null, annotations })
170+
}
171+
172+
/**
173+
* Whether a connection's tool is a read the agent may call: one we reviewed for its service, or, for a service
174+
* without a reviewed list, one the admin approved whose live definition is still the one approved and is still marked
175+
* read-only. Provider hints alone are never enough.
176+
*/
177+
export function agentReadTool(connectionUrl: string, tool: AgentToolDefinition, approved?: ReadonlyMap<string, string>): boolean {
178+
if (agentToolBlocked(tool.name)) return false
133179
const host = hostOf(connectionUrl)
134-
return host !== null && REVIEWED_READ_TOOLS[host]?.has(tool.name) === true
180+
if (host === null) return false
181+
const reviewed = REVIEWED_READ_TOOLS[host]
182+
if (reviewed) return reviewed.has(tool.name)
183+
const pinned = approved?.get(tool.name)
184+
return pinned !== undefined && agentToolMarkedReadOnly(tool) && pinned === agentToolDigest(tool)
135185
}
136186

137187
/**
@@ -151,13 +201,13 @@ export function serviceLinkDomains(connectionUrl: string): readonly string[] {
151201
return host ? SERVICE_LINK_DOMAINS[host] ?? [] : []
152202
}
153203

154-
/** An external tool the agent may call: one of its connections, and a tool that only reads. */
204+
/** An external tool the agent may call: one of its connections, and a reviewed or admin-approved read. */
155205
export function agentMayUseExternalTool(
156-
allowlist: AgentReadAllowlist,
206+
allowlist: Pick<AgentReadAllowlist, "connectionIds" | "approvedTools">,
157207
connection: { id: string; url: string },
158-
tool: { name: string },
208+
tool: AgentToolDefinition,
159209
): boolean {
160-
return allowlist.connectionIds.has(connection.id) && agentReadTool(connection.url, tool)
210+
return allowlist.connectionIds.has(connection.id) && agentReadTool(connection.url, tool, allowlist.approvedTools?.get(connection.id))
161211
}
162212

163213
export const AGENT_SOURCE_BLOCKED_MESSAGE = "Your agent may only read the sources its member turned on, and only tools that read."

‎ee/apps/den-api/src/mcp/external-capabilities.ts‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ import { compareCapabilityMatches, scoreText, tokenize } from "./search.js"
4646
import { EXTERNAL_MCP_SEARCH_CONNECTION_LIMIT, scoreExternalTool, selectExternalMcpSearchConnections } from "./external-search-selection.js"
4747
import type { CapabilityMatch, CapabilityToolAnnotations } from "./search.js"
4848
import { AGENT_SOURCE_BLOCKED_MESSAGE, agentMayUseExternalTool, agentReadAllowlist, type AgentReadAllowlist } from "./agent-read-sources.js"
49+
import { withAgentApprovedTools } from "./agent-approved-tools.js"
4950
import { DEN_MCP_WRITE_SCOPE } from "./scopes.js"
5051
import {
5152
codemodeScriptPath,
@@ -921,7 +922,8 @@ export async function searchExternalCapabilities(input: {
921922
scopes?: ReadonlySet<string>
922923
}): Promise<ExternalCapabilityMatch[]> {
923924
if (!input.member) return []
924-
const agent = input.scopes ? agentReadAllowlist(input.scopes) : null
925+
const agentScopes = input.scopes ? agentReadAllowlist(input.scopes) : null
926+
const agent = agentScopes ? await withAgentApprovedTools(agentScopes, input.organizationId) : null
925927
const queryTokens = tokenize(input.query)
926928
if (queryTokens.length === 0) return []
927929
const requestedLimit = input.limit ?? 5
@@ -1430,6 +1432,9 @@ export async function executeExternalCapability(input: {
14301432
let currentSchemaDigest: string | undefined
14311433
let schemaGuidance: ExternalMcpSchemaGuidance | undefined
14321434
const deadline = createExternalMcpLifecycleDeadline(EXTERNAL_MCP_TOOL_LIFECYCLE_TIMEOUT_MS)
1435+
// A member's background agent: its token's connections, with the tools its admin approves now.
1436+
const agentScopes = agentReadAllowlist(input.scopes)
1437+
const agent = agentScopes && !input.scopes.has(DEN_MCP_WRITE_SCOPE) ? await withAgentApprovedTools(agentScopes, input.organizationId) : null
14331438
try {
14341439
const redirectUri = redirectUriFor(input.redirectUriBase, connection.id)
14351440
type ExternalMcpTool = Awaited<ReturnType<typeof listExternalMcpTools>>[number]
@@ -1449,10 +1454,10 @@ export async function executeExternalCapability(input: {
14491454
}
14501455

14511456
// Provider-controlled hints cannot prove a tool will not mutate through its credential. The one exception is a
1452-
// member's background agent, whose token carries its sources: their reviewed read tools only (agent-read-sources.ts).
1457+
// member's background agent, whose token carries its sources: their reviewed or admin-approved read tools only
1458+
// (agent-read-sources.ts).
14531459
const requiredScope = DEN_MCP_WRITE_SCOPE
1454-
const agent = agentReadAllowlist(input.scopes)
1455-
if (agent && !input.scopes.has(requiredScope)) {
1460+
if (agent) {
14561461
if (!agentMayUseExternalTool(agent, connection, tool)) {
14571462
return { ok: false, error: "insufficient_mcp_scope", requiredScope, message: `${input.toolName}: ${AGENT_SOURCE_BLOCKED_MESSAGE}` }
14581463
}

‎ee/apps/den-api/src/routes/org/mcp-connections.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1010,6 +1010,31 @@ async function resolveExternalMcpToolCredential(
10101010
: { ok: false, message: "Connect this MCP before using its tools." }
10111011
}
10121012

1013+
/**
1014+
* The live tools/list catalog of an MCP connection, read with the credential the calling member can use (the shared
1015+
* one, or their own account). No tool is called. For admin pages that pick from a connection's tools.
1016+
*/
1017+
export async function listExternalMcpToolCatalog(
1018+
connection: ExternalMcpConnectionRow,
1019+
orgMembershipId: DenTypeId<"member">,
1020+
requestId: string,
1021+
): Promise<{ ok: true; tools: Awaited<ReturnType<typeof listExternalMcpTools>> } | { ok: false; reason: "not_ready" | "failed"; message: string }> {
1022+
const credential = await resolveExternalMcpToolCredential(connection, orgMembershipId)
1023+
if (!credential.ok) return { ok: false, reason: "not_ready", message: credential.message }
1024+
try {
1025+
return { ok: true, tools: await listExternalMcpTools(connection, await callbackRedirectUri(connection), credential.member, requestId) }
1026+
} catch (error) {
1027+
const diagnostic = externalMcpDiagnosticForResponse(error, requestId, "MCP_TOOL_DISCOVERY")
1028+
logger.error("external_mcp_tool_catalog_failed", {
1029+
connection_id: connection.id,
1030+
organization_id: connection.organizationId,
1031+
connection_endpoint: safeExternalMcpEndpointForLog(connection.url),
1032+
...externalMcpDiagnosticForLog(error, requestId, "MCP_TOOL_DISCOVERY"),
1033+
})
1034+
return { ok: false, reason: "failed", message: `Could not inspect "${connection.name}": ${diagnostic.message} Reference: ${diagnostic.referenceId}.` }
1035+
}
1036+
}
1037+
10131038
async function checkConnectionReadiness(connection: ExternalMcpConnectionRow, memberId: DenTypeId<"member">, requestId: string) {
10141039
const account = connection.credentialMode === "per_member" ? await getConnectedAccount({
10151040
organizationId: connection.organizationId, orgMembershipId: memberId, providerId: connection.id,

0 commit comments

Comments
 (0)