Skip to content

Commit af68b1e

Browse files
authored
fix(organization-search): prove resume steering end to end, lease Slack refreshes without waiting on another sweep, parse each tool call once (#10591)
- An integration test runs a deployed workflow that pauses for approval: resumed by its starter, the Organization Search block runs; resumed by another member, it refuses, and keeps refusing after a later timer resume. - The catalog test checks what construction does not guarantee: every operation a tool performs admits the executor delegation, and the Assistant has the tool. - The Slack identity sweep enrolls new organizations once, then leases with FOR UPDATE SKIP LOCKED, so a row another sweep holds is skipped rather than waited on. - An organization tool call parses its input once (prepare), so the workflow handler no longer parses twice; catalog entries drop the name and title they repeated; the Search MCP's tool runner lives in the server that uses it; block descriptions point only to the operations the block lists.
1 parent d786e63 commit af68b1e

10 files changed

Lines changed: 499 additions & 152 deletions

File tree

‎apps/sim/lib/internal/organization-search/catalog.test.ts‎

Lines changed: 33 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,46 @@
11
/**
2-
* Every organization tool reaches every surface: the MCP server registers the catalog by looping
3-
* it, and an entry added without its execution, block tool, block operation or Assistant tool
4-
* fails here rather than in a run.
2+
* Every organization tool reaches the surfaces its catalog entry does not build by itself: a
3+
* workflow run can call it, because each operation it performs admits the executor delegation,
4+
* and the Assistant has it, under its contract's name.
55
*/
6-
import { describe, expect, it, vi } from 'vitest'
7-
8-
vi.unmock('@/tools/registry')
9-
6+
import { toArray, toRecord } from '@sim/utils/object'
7+
import { describe, expect, it } from 'vitest'
108
import { assistantToolContracts } from '@/lib/api/contracts/mothership-assistant-tools'
9+
import type { ApplicationOperation } from '@/lib/core/application'
1110
import {
12-
ORGANIZATION_TOOL_CATALOG,
1311
ORGANIZATION_TOOL_NAMES,
14-
type OrganizationToolEntry,
15-
organizationSearchToolId,
12+
type OrganizationToolName,
1613
} from '@/lib/internal/organization-search/catalog'
1714
import { ORGANIZATION_TOOLS } from '@/lib/knowledge/application/organization-tool-registry'
1815
import { getRegisteredServerToolNames } from '@/lib/mothership/tools/server/router'
19-
import { OrganizationBlock } from '@/blocks/blocks/organization'
20-
import { tools } from '@/tools/registry'
16+
17+
/** The Assistant's names that differ from the Search MCP's. */
18+
const ASSISTANT_NAMES: Partial<Record<OrganizationToolName, string>> = {
19+
search: 'search_workspace',
20+
}
21+
22+
/** Inputs that steer a tool to each operation it can perform. */
23+
const INPUTS: Partial<Record<OrganizationToolName, unknown[]>> = {
24+
search_people: [{}, { personId: 'person-1' }],
25+
}
26+
27+
/** The delegated services an operation admits from an organization caller. */
28+
function organizationDelegatedServices(operation: ApplicationOperation): string[] {
29+
const organizational =
30+
'organizationOperation' in operation ? operation.organizationOperation : operation
31+
return toArray<string>(toRecord(organizational).delegatedServices)
32+
}
2133

2234
describe('organization tool catalog', () => {
23-
it.each(ORGANIZATION_TOOL_NAMES)('offers %s on every surface', (name) => {
24-
const entry: OrganizationToolEntry = ORGANIZATION_TOOL_CATALOG[name]
25-
const assistantName = entry.assistantName ?? name
26-
expect(Object.keys(ORGANIZATION_TOOLS)).toContain(name)
27-
expect(tools[organizationSearchToolId(name)]?.id).toBe(organizationSearchToolId(name))
28-
expect(OrganizationBlock.tools.access).toContain(organizationSearchToolId(name))
35+
it.each(ORGANIZATION_TOOL_NAMES)('lets a workflow run call %s', (name) => {
36+
for (const input of INPUTS[name] ?? [{}]) {
37+
const { operation } = ORGANIZATION_TOOLS[name].prepare(input)
38+
expect(organizationDelegatedServices(operation)).toContain('executor')
39+
}
40+
})
41+
42+
it.each(ORGANIZATION_TOOL_NAMES)('gives the Assistant %s', (name) => {
43+
const assistantName = ASSISTANT_NAMES[name] ?? name
2944
expect(assistantToolContracts.map((contract) => contract.id)).toContain(assistantName)
3045
expect(getRegisteredServerToolNames()).toContain(assistantName)
3146
})

‎apps/sim/lib/internal/organization-search/catalog.ts‎

Lines changed: 8 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -53,14 +53,8 @@ export const ORGANIZATION_TOOL_NAMES = [
5353
export type OrganizationToolName = (typeof ORGANIZATION_TOOL_NAMES)[number]
5454

5555
export interface OrganizationToolEntry {
56-
/** The Search MCP tool name, and the block operation that runs it. */
57-
name: OrganizationToolName
58-
/** The MCP tool's title. */
59-
title: string
60-
/** The block operation's label. */
56+
/** The block operation's label; the MCP tool's title is the same words in sentence case. */
6157
label: string
62-
/** The organization Assistant's name for it, whose contract describes it there; the MCP name when the same. */
63-
assistantName?: string
6458
/** The input every surface parses: the Search MCP schema, which reads a date without an offset as UTC. */
6559
inputSchema: z.ZodType
6660
/** The arguments a workflow run's secret could fill, projected out of what the tool returns. */
@@ -88,10 +82,7 @@ function nameOn(surface: DescriptionSurface, name: OrganizationToolName): string
8882
/** Each organization tool, by name; `ORGANIZATION_TOOL_NAMES` orders them. */
8983
export const ORGANIZATION_TOOL_CATALOG = {
9084
search: {
91-
name: 'search',
92-
title: 'Search',
9385
label: 'Search',
94-
assistantName: 'search_workspace',
9586
inputSchema: liveSearchMcpSchema,
9687
modelInputPaths: ['query', 'source', 'involving', 'nativeQueries', 'documentIds'],
9788
description: ({ surface, offers }): string => {
@@ -103,17 +94,13 @@ export const ORGANIZATION_TOOL_CATALOG = {
10394
},
10495
},
10596
read_document: {
106-
name: 'read_document',
107-
title: 'Read document',
10897
label: 'Read Document',
10998
inputSchema: readLiveDocumentMcpSchema,
11099
modelInputPaths: ['documentId', 'documentIds'],
111100
description: ({ surface }): string =>
112101
`Read live documents using the exact document IDs returned by ${nameOn(surface, 'search')}: documentId for one, or documentIds to read several in one call rather than one call each. ${surface === 'mcp' ? 'A link the user shares' : 'A link'} to a Google Drive, Gmail, Calendar, Slack, Jira, Confluence, GitHub, GitLab, Linear, Notion or Fireflies item reads the same way, without searching for it first. Access and the admin’s source settings are checked again on every read. When a document’s hasMore is true, pass its next.startChunkIndex and next.startOffset with the returned documentId to continue. Cite citationUrl when available.${surface === 'workflow' ? RUN_LOGS : ''}`,
113102
},
114103
search_people: {
115-
name: 'search_people',
116-
title: 'Search people',
117104
label: 'Search People',
118105
inputSchema: searchPeopleInputSchema,
119106
modelInputPaths: [
@@ -131,8 +118,6 @@ export const ORGANIZATION_TOOL_CATALOG = {
131118
`Look up people in this organization’s directory by name, email, title, department, or location, with query across all of them or a filter per field; managerPersonId lists someone’s direct reports. Returns each person’s title, department, location, email, start date, time zone, Slack user ID, manager, and direct report count. When exactly one person matches, or with a personId, returns that person with managerChain (direct manager first) and directReports. Covers only this organization’s people; use ${nameOn(surface, 'search')} for customers, vendors, and other outside contacts.${offers('search_experts') ? ` Who knows a topic: ${nameOn(surface, 'search_experts')}.` : ''}${surface === 'workflow' ? RUN_LOGS : ''}`,
132119
},
133120
list_my_chat_history: {
134-
name: 'list_my_chat_history',
135-
title: 'List my chat history',
136121
label: 'List My Chat History',
137122
inputSchema: listMyChatHistoryMcpSchema,
138123
modelInputPaths: [],
@@ -143,8 +128,6 @@ export const ORGANIZATION_TOOL_CATALOG = {
143128
: `List the questions the person running the workflow asked Sim between startDate (inclusive, 7 days before endDate by default) and endDate (exclusive, now by default; at most 92 days apart), newest first unless sortBy is oldest: the Assistant, agent chats, the Slack app and Search MCP chat. Each carries its time, a link to the conversation and, with includeAnswers, the start of the answer. Only their own conversations that still exist are listed. The first page carries total, the number of questions in the window; follow nextCursor for the next page.${RUN_LOGS}`,
144129
},
145130
search_experts: {
146-
name: 'search_experts',
147-
title: 'Search experts',
148131
label: 'Search Experts',
149132
inputSchema: searchExpertsMcpSchema,
150133
modelInputPaths: ['query', 'source', 'startDate', 'endDate', 'department', 'location'],
@@ -155,8 +138,6 @@ export const ORGANIZATION_TOOL_CATALOG = {
155138
: `${SEARCH_EXPERTS_DESCRIPTION.replace('items you can read', 'items the person running the workflow can read').replace('your own access', 'their own access')}${RUN_LOGS}`,
156139
},
157140
list_my_activity: {
158-
name: 'list_my_activity',
159-
title: 'List my activity',
160141
label: 'List My Activity',
161142
inputSchema: listMyActivityMcpSchema,
162143
modelInputPaths: [],
@@ -169,7 +150,7 @@ export const ORGANIZATION_TOOL_CATALOG = {
169150
return `List what ${who} did across ${their} connected sources in a date window, always newest first, each at its activity time: Slack messages and Gmail mail ${they} sent (replied when the message answers another), Google Calendar meetings ${they} organized or accepted (attended), Jira issues ${they} created or that were assigned to ${surface === 'mcp' ? 'you' : 'them'}, Confluence pages ${they} created or edited and comments ${they} wrote, GitHub issues and pull requests ${they} opened (created) and commits ${they} authored (committed), Linear issues ${they} created, Google Drive files ${they} created or edited, and the GitHub issues and pull requests and Linear issues ${they} are involved in or assigned (involved, at their last update, which may be someone else’s). Use it for standups, weekly reports and open action items. Defaults to the last 7 days; the window spans at most 92 days. Each item has a documentId for ${nameOn(surface, 'read_document')} and, when available, a citationUrl to cite. While nextCursor is present, call again with it and the same startDate, endDate and source (topK may change): pages continue without gaps, though a source that failed and recovers on a later page can return entries older than that page. sources reports every source: not_connected and reconnect carry connect.url, where ${they} connect that account. unsupported names connected sources this listing does not cover; search those for the same dates with the filters each supports. For a colleague’s activity, use ${nameOn(surface, 'search')} with involving.${surface === 'workflow' ? RUN_LOGS : ''}`
170151
},
171152
},
172-
} as const satisfies { [Name in OrganizationToolName]: OrganizationToolEntry & { name: Name } }
153+
} as const satisfies Record<OrganizationToolName, OrganizationToolEntry>
173154

174155
/** The block's operations, one per tool. */
175156
export const ORGANIZATION_SEARCH_OPERATIONS = ORGANIZATION_TOOL_NAMES.map((name) => ({
@@ -180,6 +161,12 @@ export const ORGANIZATION_SEARCH_OPERATIONS = ORGANIZATION_TOOL_NAMES.map((name)
180161
/** The internal tool that runs an operation. */
181162
export type OrganizationSearchToolId = `organization_${OrganizationToolName}`
182163

164+
/** The MCP tool's title: its block label in sentence case, such as `Read document`. */
165+
export function organizationToolTitle(name: OrganizationToolName): string {
166+
const { label } = ORGANIZATION_TOOL_CATALOG[name]
167+
return label.charAt(0) + label.slice(1).toLowerCase()
168+
}
169+
183170
/** The tool an operation runs. */
184171
export function organizationSearchToolId(
185172
operation: OrganizationToolName

‎apps/sim/lib/internal/organization-search/execute-tool.ts‎

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { createLogger } from '@sim/logger'
22
import { isPlainRecord } from '@sim/utils/object'
33
import { orchestrationFailureResponse } from '@/lib/api/server/orchestration-response'
4+
import { serializeZodIssues } from '@/lib/api/server/validation'
45
import { RESOLVED_SECRET_PROVENANCE_FIELD } from '@/lib/execution/private-tool-metadata'
56
import {
67
ORGANIZATION_TOOL_CATALOG,
@@ -13,7 +14,6 @@ import {
1314
internalToolIdentityFaultMessage,
1415
internalToolIdentityFaultStatus,
1516
} from '@/lib/internal/tool-operations/identity-faults'
16-
import { parseInternalOperationInput } from '@/lib/internal/tool-operations/parse-contract-input'
1717
import type { InternalToolOperationHandler } from '@/lib/internal/tool-operations/types'
1818
import { requireOrganizationSearchAvailable } from '@/lib/knowledge/access/availability'
1919
import { KNOWLEDGE_DELEGATION_AUDIENCE } from '@/lib/knowledge/application/authorization'
@@ -61,19 +61,22 @@ export const executeOrganizationSearchTool: InternalToolOperationHandler = async
6161
await requireOrganizationSearchAvailable(principal.organizationId)
6262
const raw = isPlainRecord(request.input) ? request.input : {}
6363
const { [RESOLVED_SECRET_PROVENANCE_FIELD]: _provenance, ...fields } = raw
64-
const { inputSchema, modelInputPaths } = ORGANIZATION_TOOL_CATALOG[name]
65-
const parsed = parseInternalOperationInput({ body: inputSchema }, fields)
66-
if (!parsed.success) return parsed.response
67-
const input: unknown = parsed.data.body
64+
const call = ORGANIZATION_TOOLS[name].prepare(fields)
65+
if (call.error)
66+
return Response.json(
67+
{ error: 'Validation error', details: serializeZodIssues(call.error) },
68+
{ status: 400 }
69+
)
70+
const { input } = call
6871
// Every argument a run's secret could fill is projected out of what the tool returns.
6972
const modelInput = isPlainRecord(input)
70-
? modelInputPaths.map((path) => input[path]).filter(Boolean)
73+
? ORGANIZATION_TOOL_CATALOG[name].modelInputPaths.map((path) => input[path]).filter(Boolean)
7174
: []
7275
return await respondWithResultProvenance(
7376
{ principal, operation: request },
7477
modelInput.length ? modelInput : undefined,
7578
(registry) =>
76-
ORGANIZATION_TOOLS[name].execute(input, {
79+
call.run({
7780
principal,
7881
organizationId: principal.organizationId,
7982
registry,

‎apps/sim/lib/knowledge/application/organization-tool-registry.ts‎

Lines changed: 36 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -44,30 +44,51 @@ interface OrganizationToolRun<Schema extends z.ZodType> {
4444
execute: (input: z.output<Schema>, context: OrganizationToolContext) => Promise<unknown>
4545
}
4646

47-
/** A tool's run, taking any input: it parses with the catalog schema before it runs. */
47+
/**
48+
* One call of a tool, its input parsed once with the catalog schema: the operation and cost it
49+
* counts as, and its run. Input that does not parse carries its error, counts as the tool's
50+
* default operation once, and fails when run.
51+
*/
52+
interface PreparedOrganizationToolCall {
53+
/** The parsed input, or the raw input when it did not parse. */
54+
input: unknown
55+
error?: z.ZodError
56+
operation: ApplicationOperation
57+
/** The operations the call counts as, or undefined for one. */
58+
cost?: number
59+
run: (context: OrganizationToolContext) => Promise<unknown>
60+
}
61+
62+
/** A tool's execution: it prepares each call from any input. */
4863
export interface OrganizationToolExecution {
49-
operation: (input: unknown) => ApplicationOperation
50-
/** The operations a call counts as, or undefined for one. */
51-
cost: (input: unknown) => number | undefined
52-
execute: (input: unknown, context: OrganizationToolContext) => Promise<unknown>
64+
prepare: (input: unknown) => PreparedOrganizationToolCall
5365
}
5466

55-
/** A tool's run over its catalog input schema, which parses every call before it runs. */
67+
/** A tool's execution over its catalog input schema. */
5668
function bind<Schema extends z.ZodType>(
5769
schema: Schema,
5870
run: OrganizationToolRun<Schema>
5971
): OrganizationToolExecution {
60-
const parsed = (input: unknown) => schema.safeParse(input)
6172
return {
62-
operation: (input) => {
63-
const result = run.operationFor && parsed(input)
64-
return result?.success && run.operationFor ? run.operationFor(result.data) : run.operation
65-
},
66-
cost: (input) => {
67-
const result = run.cost && parsed(input)
68-
return result?.success && run.cost ? run.cost(result.data) : undefined
73+
prepare: (raw) => {
74+
const parsed = schema.safeParse(raw)
75+
if (!parsed.success)
76+
return {
77+
input: raw,
78+
error: parsed.error,
79+
operation: run.operation,
80+
run: async () => {
81+
throw parsed.error
82+
},
83+
}
84+
const input = parsed.data
85+
return {
86+
input,
87+
operation: run.operationFor ? run.operationFor(input) : run.operation,
88+
cost: run.cost?.(input),
89+
run: (context) => run.execute(input, context),
90+
}
6991
},
70-
execute: (input, context) => run.execute(schema.parse(input), context),
7192
}
7293
}
7394

0 commit comments

Comments
 (0)