Skip to content

Commit 7ef574c

Browse files
authored
feat(search-assistant): person filter and people directory lookup for the organization Assistant (#10451)
* feat(search-assistant): person filter and people directory lookup for the organization Assistant The Assistant's search_workspace takes the involving filter the Search MCP gained, and organization Assistant turns get search_people, backed by the People list/get use cases through a copilot organization delegation bound to the member's private chat. Result shaping moves to lib/people/directory-lookup.ts so the MCP and the Assistant share it. A people entitlement, evaluated only on Assistant turns, tells the worker when to offer the tool. Also fixes read_document by pasted link in the Assistant: the tool no longer turns the raw link into a documentIds filter that the resolved document ID could never match. * fix(search-assistant): keep person-filtered searches out of Search tabs and people reads to Assistant turns
1 parent cdc910d commit 7ef574c

26 files changed

Lines changed: 641 additions & 179 deletions

‎apps/sim/lib/api/contracts/knowledge/mcp.ts‎

Lines changed: 1 addition & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,6 @@ import {
1111
} from '@/lib/api/contracts/mothership-assistant-tools'
1212
import { organizationIdSchema } from '@/lib/api/contracts/primitives'
1313
import { defineRouteContract } from '@/lib/api/contracts/types'
14-
import {
15-
PEOPLE_ID_MAX_LENGTH,
16-
PEOPLE_SEARCH_MAX_LENGTH,
17-
PEOPLE_SEARCH_MAX_TERMS,
18-
} from '@/lib/people/validation'
1914

2015
export const organizationKnowledgeMcpContract = defineRouteContract({
2116
method: 'POST',
@@ -58,9 +53,7 @@ export const liveSearchMcpSchema = searchWorkspaceInputFieldsSchema
5853
...mcpDateFilterFields,
5954
involving: liveSearchInvolvingSchema
6055
.optional()
61-
.describe(
62-
'Only items this person acted on: "me" (you) or a colleague\'s email address, never a name. Each source applies its own meaning (sent, authored, owns, assigned, attended; your own mail means mail you sent) and skips sources that cannot filter by person. Use it for what someone did or is assigned, not for your exchanges with others, which it would cut to one side; with an empty query and a date range it lists that person\'s activity.'
63-
),
56+
.describe(searchWorkspaceInputFieldsSchema.shape.involving.description ?? ''),
6457
topK: searchWorkspaceInputFieldsSchema.shape.topK
6558
.unwrap()
6659
.optional()
@@ -138,35 +131,3 @@ export const chatSearchMcpSchema = workspaceSearchFiltersSchema
138131
.describe('The chatId of an earlier chat answer, to ask a follow-up in that conversation.'),
139132
})
140133
.strict()
141-
142-
export const searchPeopleMcpSchema = z
143-
.object({
144-
query: z
145-
.string()
146-
.trim()
147-
.min(1)
148-
.max(PEOPLE_SEARCH_MAX_LENGTH)
149-
.optional()
150-
.describe(
151-
`Up to ${PEOPLE_SEARCH_MAX_TERMS} words from a name, email, title, department, or location; a person matches when every word appears in one of them.`
152-
),
153-
personId: z
154-
.string()
155-
.min(1)
156-
.max(PEOPLE_ID_MAX_LENGTH)
157-
.optional()
158-
.describe(
159-
'A personId from an earlier result, to show that person with their managers and direct reports. Used instead of query.'
160-
),
161-
cursor: z
162-
.string()
163-
.min(1)
164-
.max(1024)
165-
.optional()
166-
.describe('nextCursor from the previous page of the same query.'),
167-
})
168-
.strict()
169-
.refine((input) => !input.personId || (input.query === undefined && !input.cursor), {
170-
path: ['personId'],
171-
message: 'Pass either personId or a query with its cursor, not both.',
172-
})

‎apps/sim/lib/api/contracts/mothership-assistant-tools.ts‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -235,6 +235,15 @@ export const searchWorkspaceInputFieldsSchema = workspaceSearchFiltersSchema.ext
235235
.describe(
236236
'Search terms, without dates already supplied as filters. May be empty for a live listing with a date bound or sortBy newest or oldest where supported, or use an explicit native browse mode. Notion date-only search depends on plan capabilities.'
237237
),
238+
involving: z
239+
.string()
240+
.trim()
241+
.min(1)
242+
.max(254)
243+
.optional()
244+
.describe(
245+
'Only items this person acted on: "me" (you) or a colleague\'s email address, never a name. Each source applies its own meaning (sent, authored, owns, assigned, attended; your own mail means mail you sent) and skips sources that cannot filter by person. Use it for what someone did or is assigned, not for your exchanges with others, which it would cut to one side; with an empty query and a date range it lists that person\'s activity.'
246+
),
238247
topK: z
239248
.number()
240249
.int()
@@ -323,6 +332,42 @@ export const readDocumentInputSchema = z.object({
323332
),
324333
})
325334

335+
/**
336+
* Organization directory lookups. The bounds mirror the People page's search limits
337+
* (`lib/people/validation`) as literals, so the worker's generated copy stays standalone.
338+
*/
339+
export const searchPeopleInputSchema = z
340+
.object({
341+
query: z
342+
.string()
343+
.trim()
344+
.min(1)
345+
.max(200)
346+
.optional()
347+
.describe(
348+
'Up to 8 words from a name, email, title, department, or location; a person matches when every word appears in one of them.'
349+
),
350+
personId: z
351+
.string()
352+
.min(1)
353+
.max(255)
354+
.optional()
355+
.describe(
356+
'A personId from an earlier result, to show that person with their managers and direct reports. Used instead of query.'
357+
),
358+
cursor: z
359+
.string()
360+
.min(1)
361+
.max(1024)
362+
.optional()
363+
.describe('nextCursor from the previous page of the same query.'),
364+
})
365+
.strict()
366+
.refine((input) => !input.personId || (input.query === undefined && !input.cursor), {
367+
path: ['personId'],
368+
message: 'Pass either personId or a query with its cursor, not both.',
369+
})
370+
326371
/** Connection requests name a provider and optionally an owned account to repair. */
327372
export const oauthGetAuthLinkInputSchema = z.object({
328373
providerName: z
@@ -386,6 +431,13 @@ export const assistantToolContracts = [
386431
description: 'Read more context from an accessible connected-source document.',
387432
inputSchema: readDocumentInputSchema,
388433
},
434+
{
435+
id: 'search_people',
436+
route: 'sim',
437+
description:
438+
'Look up people in this organization’s directory by name, email, title, department, or location. Returns each person’s title, department, location, email, and manager. 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 search_workspace for customers, vendors, and other outside contacts.',
439+
inputSchema: searchPeopleInputSchema,
440+
},
389441
{
390442
id: 'oauth_get_auth_link',
391443
route: 'sim',

‎apps/sim/lib/knowledge/mcp/people.ts‎

Lines changed: 10 additions & 119 deletions
Original file line numberDiff line numberDiff line change
@@ -1,81 +1,14 @@
11
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
22
import type { Principal } from '@sim/auth/principal'
3-
import { createLogger } from '@sim/logger'
4-
import { getErrorMessage } from '@sim/utils/errors'
53
import type { NextRequest } from 'next/server'
6-
import {
7-
organizationKnowledgeMcpContract,
8-
searchPeopleMcpSchema,
9-
} from '@/lib/api/contracts/knowledge/mcp'
10-
import type { PersonSummary } from '@/lib/api/contracts/people'
11-
import { cursorRoute, cursorScopeKey } from '@/lib/api/cursor-binding'
12-
import { OrchestrationError } from '@/lib/core/orchestration/types'
4+
import { searchPeopleInputSchema } from '@/lib/api/contracts/mothership-assistant-tools'
135
import {
146
KNOWLEDGE_MCP_READ_ONLY,
157
type KnowledgeMcpToolRunner,
168
projectResult,
179
} from '@/lib/knowledge/mcp/tool-runner'
1810
import { getPerson, listPeople } from '@/lib/people/application/use-cases'
19-
import { isPeopleEnabled } from '@/lib/people/feature-flag'
20-
import type { PersonRecord } from '@/lib/people/repository'
21-
import { readSortedCursor, writeSortedCursor } from '@/app/api/v2/lib/response'
22-
23-
const logger = createLogger('KnowledgeMcpPeople')
24-
25-
/** Said when a query matches no one, so a client looks for people outside the organization in search. */
26-
export const NO_PEOPLE_MATCH_NOTE =
27-
'No one in this organization’s directory matches. The directory lists only people in this organization; use search for anyone else, such as customer or vendor contacts.'
28-
29-
/**
30-
* Whether `principal` may look people up in `organizationId`: People is on there and the
31-
* directory is open to them. Asked when listing tools, so a client whose organization has no
32-
* People directory, or who may not browse it, is never offered the tool. A lookup that fails hides
33-
* the tool rather than failing the listing around it.
34-
*/
35-
export async function canSearchPeople(
36-
principal: Principal,
37-
organizationId: string
38-
): Promise<boolean> {
39-
try {
40-
if (!(await isPeopleEnabled(organizationId))) return false
41-
await listPeople.authorize({ principal, input: { organizationId } })
42-
return true
43-
} catch (error) {
44-
if (!(error instanceof OrchestrationError))
45-
logger.warn('Could not resolve Search MCP people access', {
46-
organizationId,
47-
error: getErrorMessage(error),
48-
})
49-
return false
50-
}
51-
}
52-
53-
function summaryFacts(person: PersonSummary) {
54-
return {
55-
personId: person.memberId,
56-
name: person.name,
57-
...(person.title ? { title: person.title } : {}),
58-
}
59-
}
60-
61-
function reportFacts(report: PersonSummary & { department: string | null; reportCount: number }) {
62-
return {
63-
...summaryFacts(report),
64-
...(report.department ? { department: report.department } : {}),
65-
directReports: report.reportCount,
66-
}
67-
}
68-
69-
function personFacts(person: PersonRecord) {
70-
const { department, location, startDate } = person
71-
return {
72-
...summaryFacts(person),
73-
email: person.email,
74-
...(department ? { department } : {}),
75-
...(location ? { location } : {}),
76-
...(startDate ? { startDate } : {}),
77-
}
78-
}
11+
import { findDirectoryPeople, readDirectoryPerson } from '@/lib/people/directory-lookup'
7912

8013
interface SearchPeopleToolContext {
8114
execute: KnowledgeMcpToolRunner
@@ -93,70 +26,28 @@ export function registerSearchPeopleTool(
9326
server: McpServer,
9427
{ execute, principal, organizationId, request }: SearchPeopleToolContext
9528
) {
96-
const detail = async (memberId: string) => {
97-
const { person, chain, reports, totalReports } = await getPerson.execute({
98-
principal,
99-
input: { organizationId, memberId },
100-
request,
101-
})
102-
return {
103-
person: {
104-
...personFacts(person),
105-
...(chain.length ? { managerChain: chain.map(summaryFacts) } : {}),
106-
...(reports.length ? { directReports: reports.map(reportFacts) } : {}),
107-
totalDirectReports: totalReports,
108-
...(totalReports > reports.length
109-
? {
110-
note: `directReports lists the first ${reports.length} of ${totalReports}; search by department or title to find the others.`,
111-
}
112-
: {}),
113-
},
114-
}
115-
}
116-
11729
server.registerTool(
11830
'search_people',
11931
{
12032
title: 'Search people',
12133
description:
12234
'Look up people in this organization’s directory by name, email, title, department, or location. Returns each person’s title, department, location, email, and manager. 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 search for customers, vendors, and other outside contacts.',
123-
inputSchema: searchPeopleMcpSchema,
35+
inputSchema: searchPeopleInputSchema,
12436
annotations: KNOWLEDGE_MCP_READ_ONLY,
12537
},
12638
async (input: unknown, extra: { signal: AbortSignal }) => {
127-
const personId = searchPeopleMcpSchema.safeParse(input).data?.personId
39+
const personId = searchPeopleInputSchema.safeParse(input).data?.personId
12840
if (personId)
12941
return execute('search_people', getPerson.operation, extra.signal, async (registry) =>
130-
projectResult(await detail(personId), registry)
42+
projectResult(
43+
await readDirectoryPerson({ principal, organizationId, request, personId }),
44+
registry
45+
)
13146
)
13247
return execute('search_people', listPeople.operation, extra.signal, async (registry) => {
133-
const { query, cursor } = searchPeopleMcpSchema.parse(input)
134-
const scope = cursorScopeKey(
135-
cursorRoute(organizationKnowledgeMcpContract, { organizationId }),
136-
{ tool: 'search_people', query }
137-
)
138-
const page = await listPeople.execute({
139-
principal,
140-
input: {
141-
organizationId,
142-
search: query,
143-
cursorKeys: readSortedCursor(cursor, 'name', 'asc', scope),
144-
},
145-
request,
146-
})
147-
const [only] = page.data
148-
if (only && page.data.length === 1 && !cursor)
149-
return projectResult(await detail(only.memberId), registry)
150-
const nextCursor = writeSortedCursor(page.nextCursorKeys, 'name', 'asc', scope)
48+
const { query, cursor } = searchPeopleInputSchema.parse(input)
15149
return projectResult(
152-
{
153-
people: page.data.map((person) => ({
154-
...personFacts(person),
155-
...(person.manager ? { manager: person.manager.name } : {}),
156-
})),
157-
...(nextCursor ? { nextCursor } : {}),
158-
...(page.data.length ? {} : { note: NO_PEOPLE_MATCH_NOTE }),
159-
},
50+
await findDirectoryPeople({ principal, organizationId, request, query, cursor }),
16051
registry
16152
)
16253
})

‎apps/sim/lib/knowledge/mcp/route-handler.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,10 @@ import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
1515
import { knowledgeOperations } from '@/lib/knowledge/application/operations'
1616
import { readSearchIndex } from '@/lib/knowledge/application/sim-search'
1717
import { withSearchMcpAuthChallenge } from '@/lib/knowledge/mcp/oauth-metadata'
18-
import { canSearchPeople } from '@/lib/knowledge/mcp/people'
1918
import { createKnowledgeMcpServer } from '@/lib/knowledge/mcp/server'
2019
import { repairToolCallMessage, toolCallInputIssues } from '@/lib/knowledge/mcp/tool-arguments'
2120
import { getSearchMcpUrl } from '@/lib/knowledge/mcp/urls'
21+
import { canLookUpPeople } from '@/lib/people/directory-lookup'
2222
import { v2CaughtOrchestrationError, v2Error } from '@/app/api/v2/lib/response'
2323

2424
const logger = createLogger('KnowledgeMcp')
@@ -34,7 +34,7 @@ async function offersSearchPeople(
3434
) {
3535
if (message.method === 'tools/call')
3636
return isRecordLike(message.params) && message.params.name === 'search_people'
37-
return message.method === 'tools/list' && canSearchPeople(principal, organizationId)
37+
return message.method === 'tools/list' && canLookUpPeople(principal, organizationId)
3838
}
3939

4040
function mcpAuth(resource: string) {

‎apps/sim/lib/knowledge/mcp/server.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,8 +61,8 @@ vi.mock('@/lib/knowledge/application/chat', () => ({
6161
}))
6262

6363
import { OrchestrationError } from '@/lib/core/orchestration/types'
64-
import { NO_PEOPLE_MATCH_NOTE } from '@/lib/knowledge/mcp/people'
6564
import { createKnowledgeMcpServer } from '@/lib/knowledge/mcp/server'
65+
import { NO_PEOPLE_MATCH_NOTE } from '@/lib/people/directory-lookup'
6666
import {
6767
LIVE_DATE_ORDER_MESSAGE,
6868
LIVE_MORE_RANKED_BELOW_MESSAGE,

‎apps/sim/lib/knowledge/mcp/tool-arguments.ts‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,12 @@ import {
44
chatSearchMcpSchema,
55
liveSearchMcpSchema,
66
readLiveDocumentMcpSchema,
7-
searchPeopleMcpSchema,
87
} from '@/lib/api/contracts/knowledge/mcp'
98
import { mcpToolCallParamsSchema } from '@/lib/api/contracts/mcp'
10-
import { liveSearchProviderSchema } from '@/lib/api/contracts/mothership-assistant-tools'
9+
import {
10+
liveSearchProviderSchema,
11+
searchPeopleInputSchema,
12+
} from '@/lib/api/contracts/mothership-assistant-tools'
1113

1214
/** Search filters a client sometimes writes on each native query instead of on the search. */
1315
const SEARCH_FILTERS_ON_NATIVE_QUERIES = [
@@ -24,7 +26,7 @@ const TOOL_INPUT_SCHEMAS = new Map<string, z.ZodType>([
2426
['search', liveSearchMcpSchema],
2527
['read_document', readLiveDocumentMcpSchema],
2628
['chat', chatSearchMcpSchema],
27-
['search_people', searchPeopleMcpSchema],
29+
['search_people', searchPeopleInputSchema],
2830
])
2931

3032
function readToolCall(message: Record<string, unknown>) {
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import type { OrganizationDelegatedPrincipal } from '@sim/auth/principal'
2+
import { OrchestrationError } from '@/lib/core/orchestration/types'
3+
import {
4+
COPILOT_APPLICATION_DELEGATION_TTL_MS,
5+
type CopilotExecutionContext,
6+
createTrustedOrganizationCopilotPrincipal,
7+
requireTrustedOrganizationCopilotContext,
8+
} from '@/lib/mothership/auth/application-delegation'
9+
import { authorizeOrganizationChatDelegation } from '@/lib/mothership/chat/organization-chats'
10+
import { peopleOperations } from '@/lib/people/application/operations'
11+
12+
interface CopilotPeopleScope {
13+
principal: OrganizationDelegatedPrincipal
14+
organizationId: string
15+
}
16+
17+
/**
18+
* Runs a People directory read for the organization Assistant, the only mode Sim grants the
19+
* `people` entitlement in. The subject and organization come from the trusted turn, the
20+
* delegation is bound to the member's private chat, and the People use cases the read calls
21+
* still check the feature, the membership and the directory capability.
22+
*/
23+
export async function executeCopilotPeopleRead<R>(
24+
context: CopilotExecutionContext | undefined,
25+
read: (scope: CopilotPeopleScope) => Promise<R>
26+
): Promise<R> {
27+
const trusted = requireTrustedOrganizationCopilotContext(context)
28+
if (context?.requestMode !== 'assistant')
29+
throw new OrchestrationError(
30+
'forbidden',
31+
'The People directory is available only in organization Assistant conversations'
32+
)
33+
const principal = createTrustedOrganizationCopilotPrincipal(
34+
{ ...trusted, delegationId: trusted.toolCallId },
35+
{
36+
audience: peopleOperations.list.delegationAudience,
37+
ttlMs: COPILOT_APPLICATION_DELEGATION_TTL_MS,
38+
}
39+
)
40+
await authorizeOrganizationChatDelegation.execute({ principal })
41+
return read({ principal, organizationId: trusted.organizationId })
42+
}

0 commit comments

Comments
 (0)