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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 33 additions & 18 deletions apps/sim/lib/internal/organization-search/catalog.test.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,46 @@
/**
* Every organization tool reaches every surface: the MCP server registers the catalog by looping
* it, and an entry added without its execution, block tool, block operation or Assistant tool
* fails here rather than in a run.
* Every organization tool reaches the surfaces its catalog entry does not build by itself: a
* workflow run can call it, because each operation it performs admits the executor delegation,
* and the Assistant has it, under its contract's name.
*/
import { describe, expect, it, vi } from 'vitest'

vi.unmock('@/tools/registry')

import { toArray, toRecord } from '@sim/utils/object'
import { describe, expect, it } from 'vitest'
import { assistantToolContracts } from '@/lib/api/contracts/mothership-assistant-tools'
import type { ApplicationOperation } from '@/lib/core/application'
import {
ORGANIZATION_TOOL_CATALOG,
ORGANIZATION_TOOL_NAMES,
type OrganizationToolEntry,
organizationSearchToolId,
type OrganizationToolName,
} from '@/lib/internal/organization-search/catalog'
import { ORGANIZATION_TOOLS } from '@/lib/knowledge/application/organization-tool-registry'
import { getRegisteredServerToolNames } from '@/lib/mothership/tools/server/router'
import { OrganizationBlock } from '@/blocks/blocks/organization'
import { tools } from '@/tools/registry'

/** The Assistant's names that differ from the Search MCP's. */
const ASSISTANT_NAMES: Partial<Record<OrganizationToolName, string>> = {
search: 'search_workspace',
}

/** Inputs that steer a tool to each operation it can perform. */
const INPUTS: Partial<Record<OrganizationToolName, unknown[]>> = {
search_people: [{}, { personId: 'person-1' }],
}

/** The delegated services an operation admits from an organization caller. */
function organizationDelegatedServices(operation: ApplicationOperation): string[] {
const organizational =
'organizationOperation' in operation ? operation.organizationOperation : operation
return toArray<string>(toRecord(organizational).delegatedServices)
}

describe('organization tool catalog', () => {
it.each(ORGANIZATION_TOOL_NAMES)('offers %s on every surface', (name) => {
const entry: OrganizationToolEntry = ORGANIZATION_TOOL_CATALOG[name]
const assistantName = entry.assistantName ?? name
expect(Object.keys(ORGANIZATION_TOOLS)).toContain(name)
expect(tools[organizationSearchToolId(name)]?.id).toBe(organizationSearchToolId(name))
expect(OrganizationBlock.tools.access).toContain(organizationSearchToolId(name))
it.each(ORGANIZATION_TOOL_NAMES)('lets a workflow run call %s', (name) => {
for (const input of INPUTS[name] ?? [{}]) {
const { operation } = ORGANIZATION_TOOLS[name].prepare(input)
expect(organizationDelegatedServices(operation)).toContain('executor')
}
})

it.each(ORGANIZATION_TOOL_NAMES)('gives the Assistant %s', (name) => {
const assistantName = ASSISTANT_NAMES[name] ?? name
expect(assistantToolContracts.map((contract) => contract.id)).toContain(assistantName)
expect(getRegisteredServerToolNames()).toContain(assistantName)
})
Expand Down
29 changes: 8 additions & 21 deletions apps/sim/lib/internal/organization-search/catalog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,14 +53,8 @@ export const ORGANIZATION_TOOL_NAMES = [
export type OrganizationToolName = (typeof ORGANIZATION_TOOL_NAMES)[number]

export interface OrganizationToolEntry {
/** The Search MCP tool name, and the block operation that runs it. */
name: OrganizationToolName
/** The MCP tool's title. */
title: string
/** The block operation's label. */
/** The block operation's label; the MCP tool's title is the same words in sentence case. */
label: string
/** The organization Assistant's name for it, whose contract describes it there; the MCP name when the same. */
assistantName?: string
/** The input every surface parses: the Search MCP schema, which reads a date without an offset as UTC. */
inputSchema: z.ZodType
/** The arguments a workflow run's secret could fill, projected out of what the tool returns. */
Expand Down Expand Up @@ -88,10 +82,7 @@ function nameOn(surface: DescriptionSurface, name: OrganizationToolName): string
/** Each organization tool, by name; `ORGANIZATION_TOOL_NAMES` orders them. */
export const ORGANIZATION_TOOL_CATALOG = {
search: {
name: 'search',
title: 'Search',
label: 'Search',
assistantName: 'search_workspace',
inputSchema: liveSearchMcpSchema,
modelInputPaths: ['query', 'source', 'involving', 'nativeQueries', 'documentIds'],
description: ({ surface, offers }): string => {
Expand All @@ -103,17 +94,13 @@ export const ORGANIZATION_TOOL_CATALOG = {
},
},
read_document: {
name: 'read_document',
title: 'Read document',
label: 'Read Document',
inputSchema: readLiveDocumentMcpSchema,
modelInputPaths: ['documentId', 'documentIds'],
description: ({ surface }): string =>
`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 : ''}`,
},
search_people: {
name: 'search_people',
title: 'Search people',
label: 'Search People',
inputSchema: searchPeopleInputSchema,
modelInputPaths: [
Expand All @@ -131,8 +118,6 @@ export const ORGANIZATION_TOOL_CATALOG = {
`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 : ''}`,
},
list_my_chat_history: {
name: 'list_my_chat_history',
title: 'List my chat history',
label: 'List My Chat History',
inputSchema: listMyChatHistoryMcpSchema,
modelInputPaths: [],
Expand All @@ -143,8 +128,6 @@ export const ORGANIZATION_TOOL_CATALOG = {
: `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}`,
},
search_experts: {
name: 'search_experts',
title: 'Search experts',
label: 'Search Experts',
inputSchema: searchExpertsMcpSchema,
modelInputPaths: ['query', 'source', 'startDate', 'endDate', 'department', 'location'],
Expand All @@ -155,8 +138,6 @@ export const ORGANIZATION_TOOL_CATALOG = {
: `${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}`,
},
list_my_activity: {
name: 'list_my_activity',
title: 'List my activity',
label: 'List My Activity',
inputSchema: listMyActivityMcpSchema,
modelInputPaths: [],
Expand All @@ -169,7 +150,7 @@ export const ORGANIZATION_TOOL_CATALOG = {
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 : ''}`
},
},
} as const satisfies { [Name in OrganizationToolName]: OrganizationToolEntry & { name: Name } }
} as const satisfies Record<OrganizationToolName, OrganizationToolEntry>

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

/** The MCP tool's title: its block label in sentence case, such as `Read document`. */
export function organizationToolTitle(name: OrganizationToolName): string {
const { label } = ORGANIZATION_TOOL_CATALOG[name]
return label.charAt(0) + label.slice(1).toLowerCase()
}

/** The tool an operation runs. */
export function organizationSearchToolId(
operation: OrganizationToolName
Expand Down
17 changes: 10 additions & 7 deletions apps/sim/lib/internal/organization-search/execute-tool.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { createLogger } from '@sim/logger'
import { isPlainRecord } from '@sim/utils/object'
import { orchestrationFailureResponse } from '@/lib/api/server/orchestration-response'
import { serializeZodIssues } from '@/lib/api/server/validation'
import { RESOLVED_SECRET_PROVENANCE_FIELD } from '@/lib/execution/private-tool-metadata'
import {
ORGANIZATION_TOOL_CATALOG,
Expand All @@ -13,7 +14,6 @@ import {
internalToolIdentityFaultMessage,
internalToolIdentityFaultStatus,
} from '@/lib/internal/tool-operations/identity-faults'
import { parseInternalOperationInput } from '@/lib/internal/tool-operations/parse-contract-input'
import type { InternalToolOperationHandler } from '@/lib/internal/tool-operations/types'
import { requireOrganizationSearchAvailable } from '@/lib/knowledge/access/availability'
import { KNOWLEDGE_DELEGATION_AUDIENCE } from '@/lib/knowledge/application/authorization'
Expand Down Expand Up @@ -61,19 +61,22 @@ export const executeOrganizationSearchTool: InternalToolOperationHandler = async
await requireOrganizationSearchAvailable(principal.organizationId)
const raw = isPlainRecord(request.input) ? request.input : {}
const { [RESOLVED_SECRET_PROVENANCE_FIELD]: _provenance, ...fields } = raw
const { inputSchema, modelInputPaths } = ORGANIZATION_TOOL_CATALOG[name]
const parsed = parseInternalOperationInput({ body: inputSchema }, fields)
if (!parsed.success) return parsed.response
const input: unknown = parsed.data.body
const call = ORGANIZATION_TOOLS[name].prepare(fields)
if (call.error)
return Response.json(
{ error: 'Validation error', details: serializeZodIssues(call.error) },
{ status: 400 }
)
const { input } = call
// Every argument a run's secret could fill is projected out of what the tool returns.
const modelInput = isPlainRecord(input)
? modelInputPaths.map((path) => input[path]).filter(Boolean)
? ORGANIZATION_TOOL_CATALOG[name].modelInputPaths.map((path) => input[path]).filter(Boolean)
: []
return await respondWithResultProvenance(
{ principal, operation: request },
modelInput.length ? modelInput : undefined,
(registry) =>
ORGANIZATION_TOOLS[name].execute(input, {
call.run({
principal,
organizationId: principal.organizationId,
registry,
Expand Down
51 changes: 36 additions & 15 deletions apps/sim/lib/knowledge/application/organization-tool-registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,30 +44,51 @@ interface OrganizationToolRun<Schema extends z.ZodType> {
execute: (input: z.output<Schema>, context: OrganizationToolContext) => Promise<unknown>
}

/** A tool's run, taking any input: it parses with the catalog schema before it runs. */
/**
* One call of a tool, its input parsed once with the catalog schema: the operation and cost it
* counts as, and its run. Input that does not parse carries its error, counts as the tool's
* default operation once, and fails when run.
*/
interface PreparedOrganizationToolCall {
/** The parsed input, or the raw input when it did not parse. */
input: unknown
error?: z.ZodError
operation: ApplicationOperation
/** The operations the call counts as, or undefined for one. */
cost?: number
run: (context: OrganizationToolContext) => Promise<unknown>
}

/** A tool's execution: it prepares each call from any input. */
export interface OrganizationToolExecution {
operation: (input: unknown) => ApplicationOperation
/** The operations a call counts as, or undefined for one. */
cost: (input: unknown) => number | undefined
execute: (input: unknown, context: OrganizationToolContext) => Promise<unknown>
prepare: (input: unknown) => PreparedOrganizationToolCall
}

/** A tool's run over its catalog input schema, which parses every call before it runs. */
/** A tool's execution over its catalog input schema. */
function bind<Schema extends z.ZodType>(
schema: Schema,
run: OrganizationToolRun<Schema>
): OrganizationToolExecution {
const parsed = (input: unknown) => schema.safeParse(input)
return {
operation: (input) => {
const result = run.operationFor && parsed(input)
return result?.success && run.operationFor ? run.operationFor(result.data) : run.operation
},
cost: (input) => {
const result = run.cost && parsed(input)
return result?.success && run.cost ? run.cost(result.data) : undefined
prepare: (raw) => {
const parsed = schema.safeParse(raw)
if (!parsed.success)
return {
input: raw,
error: parsed.error,
operation: run.operation,
run: async () => {
throw parsed.error
},
}
const input = parsed.data
return {
input,
operation: run.operationFor ? run.operationFor(input) : run.operation,
cost: run.cost?.(input),
run: (context) => run.execute(input, context),
}
},
execute: (input, context) => run.execute(schema.parse(input), context),
}
}

Expand Down
Loading
Loading