Skip to content

Commit 9ba6dbc

Browse files
authored
feat(search-mcp): look up people in the organization directory (#10435)
* feat(search-mcp): look up people in the organization directory Adds a search_people tool to the Search MCP server, offered when the organization has People on and the caller may browse its directory. It reads through the People list and profile use cases, now admitting personal API keys and OAuth tokens under search:read. A search matches people who hold every word in their name, email, title, department, or location; one match returns that person's manager chain and direct reports in the same call. * fix(search-mcp): validate people lookup arguments and commit before validating the check * fix(search-mcp): state the people search word cap and always send report counts * chore(search-mcp): drop a benchmark-only preload committed by mistake
1 parent faef297 commit 9ba6dbc

15 files changed

Lines changed: 34387 additions & 15 deletions

File tree

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

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,11 @@ import {
88
} from '@/lib/api/contracts/mothership-assistant-tools'
99
import { organizationIdSchema } from '@/lib/api/contracts/primitives'
1010
import { defineRouteContract } from '@/lib/api/contracts/types'
11+
import {
12+
PEOPLE_ID_MAX_LENGTH,
13+
PEOPLE_SEARCH_MAX_LENGTH,
14+
PEOPLE_SEARCH_MAX_TERMS,
15+
} from '@/lib/people/validation'
1116

1217
export const organizationKnowledgeMcpContract = defineRouteContract({
1318
method: 'POST',
@@ -125,3 +130,35 @@ export const chatSearchMcpSchema = workspaceSearchFiltersSchema
125130
.describe('The chatId of an earlier chat answer, to ask a follow-up in that conversation.'),
126131
})
127132
.strict()
133+
134+
export const searchPeopleMcpSchema = z
135+
.object({
136+
query: z
137+
.string()
138+
.trim()
139+
.min(1)
140+
.max(PEOPLE_SEARCH_MAX_LENGTH)
141+
.optional()
142+
.describe(
143+
`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.`
144+
),
145+
personId: z
146+
.string()
147+
.min(1)
148+
.max(PEOPLE_ID_MAX_LENGTH)
149+
.optional()
150+
.describe(
151+
'A personId from an earlier result, to show that person with their managers and direct reports. Used instead of query.'
152+
),
153+
cursor: z
154+
.string()
155+
.min(1)
156+
.max(1024)
157+
.optional()
158+
.describe('nextCursor from the previous page of the same query.'),
159+
})
160+
.strict()
161+
.refine((input) => !input.personId || (input.query === undefined && !input.cursor), {
162+
path: ['personId'],
163+
message: 'Pass either personId or a query with its cursor, not both.',
164+
})

‎apps/sim/lib/auth/oauth-provider.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ export const OAUTH_SCOPE_DESCRIPTIONS: Record<OAuthScope, string> = {
9595
[OAUTH_API_READ_SCOPE]: 'Read your workspaces, workflows, files, tables, and logs',
9696
[OAUTH_API_WRITE_SCOPE]: 'Read, create, change, run, and delete resources in your workspaces',
9797
[OAUTH_SEARCH_READ_SCOPE]:
98-
'Search and read documents you can access, and start private Sim Search conversations',
98+
'Search and read documents you can access, look up people in your organization, and start private Sim Search conversations',
9999
}
100100

101101
/**
Lines changed: 165 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,165 @@
1+
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
2+
import type { Principal } from '@sim/auth/principal'
3+
import { createLogger } from '@sim/logger'
4+
import { getErrorMessage } from '@sim/utils/errors'
5+
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'
13+
import {
14+
KNOWLEDGE_MCP_READ_ONLY,
15+
type KnowledgeMcpToolRunner,
16+
projectResult,
17+
} from '@/lib/knowledge/mcp/tool-runner'
18+
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+
}
79+
80+
interface SearchPeopleToolContext {
81+
execute: KnowledgeMcpToolRunner
82+
principal: Principal
83+
organizationId: string
84+
request: NextRequest
85+
}
86+
87+
/**
88+
* Registers `search_people`: the organization's People directory through the same use cases the
89+
* People page reads. A query that finds one person, or a personId, returns that person with their
90+
* reporting line, so "who is X's manager" or "who reports to X" takes one call.
91+
*/
92+
export function registerSearchPeopleTool(
93+
server: McpServer,
94+
{ execute, principal, organizationId, request }: SearchPeopleToolContext
95+
) {
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+
117+
server.registerTool(
118+
'search_people',
119+
{
120+
title: 'Search people',
121+
description:
122+
'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,
124+
annotations: KNOWLEDGE_MCP_READ_ONLY,
125+
},
126+
async (input: unknown, extra: { signal: AbortSignal }) => {
127+
const personId = searchPeopleMcpSchema.safeParse(input).data?.personId
128+
if (personId)
129+
return execute('search_people', getPerson.operation, extra.signal, async (registry) =>
130+
projectResult(await detail(personId), registry)
131+
)
132+
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)
151+
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+
},
160+
registry
161+
)
162+
})
163+
}
164+
)
165+
}

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

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1+
import type { Principal } from '@sim/auth/principal'
12
import { createLogger } from '@sim/logger'
3+
import { isRecordLike } from '@sim/utils/object'
24
import type { NextRequest } from 'next/server'
35
import { organizationKnowledgeMcpContract } from '@/lib/api/contracts/knowledge/mcp'
46
import { parseRequest } from '@/lib/api/server'
@@ -13,13 +15,28 @@ import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
1315
import { knowledgeOperations } from '@/lib/knowledge/application/operations'
1416
import { readSearchIndex } from '@/lib/knowledge/application/sim-search'
1517
import { withSearchMcpAuthChallenge } from '@/lib/knowledge/mcp/oauth-metadata'
18+
import { canSearchPeople } from '@/lib/knowledge/mcp/people'
1619
import { createKnowledgeMcpServer } from '@/lib/knowledge/mcp/server'
1720
import { repairToolCallMessage, toolCallInputIssues } from '@/lib/knowledge/mcp/tool-arguments'
1821
import { getSearchMcpUrl } from '@/lib/knowledge/mcp/urls'
1922
import { v2CaughtOrchestrationError, v2Error } from '@/app/api/v2/lib/response'
2023

2124
const logger = createLogger('KnowledgeMcp')
2225

26+
/**
27+
* Whether this message needs search_people registered. A call to it is authorized by its own use
28+
* cases, so only a tools/list asks whether the caller may browse People, and other messages skip it.
29+
*/
30+
async function offersSearchPeople(
31+
message: Record<string, unknown>,
32+
principal: Principal,
33+
organizationId: string
34+
) {
35+
if (message.method === 'tools/call')
36+
return isRecordLike(message.params) && message.params.name === 'search_people'
37+
return message.method === 'tools/list' && canSearchPeople(principal, organizationId)
38+
}
39+
2340
function mcpAuth(resource: string) {
2441
return mcpCredentialAuth({ resource, allowUnboundApiTokens: true })
2542
}
@@ -62,6 +79,7 @@ export function createKnowledgeMcpHandlers() {
6279
request,
6380
auth: admission.auth,
6481
...parsed.data.params,
82+
searchPeople: await offersSearchPeople(message, admission.auth.principal, organizationId),
6583
})
6684
return await serveStatelessMcp(server, request, message)
6785
} catch (error) {

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

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,12 @@ const hoisted = vi.hoisted(() => ({
2121
rateLimit: vi.fn(),
2222
afterResponse: vi.fn<(task: () => Promise<void>) => void>(),
2323
recordActivity: vi.fn(),
24+
listPeople: vi.fn(),
25+
getPerson: vi.fn(),
26+
}))
27+
vi.mock('@/lib/people/application/use-cases', () => ({
28+
listPeople: { operation: { id: 'organization.people.list' }, execute: hoisted.listPeople },
29+
getPerson: { execute: hoisted.getPerson },
2430
}))
2531
vi.mock('@/lib/core/utils/after-response', () => ({ afterResponse: hoisted.afterResponse }))
2632
vi.mock('@/lib/knowledge/mcp/activity', () => ({
@@ -55,6 +61,7 @@ vi.mock('@/lib/knowledge/application/chat', () => ({
5561
}))
5662

5763
import { OrchestrationError } from '@/lib/core/orchestration/types'
64+
import { NO_PEOPLE_MATCH_NOTE } from '@/lib/knowledge/mcp/people'
5865
import { createKnowledgeMcpServer } from '@/lib/knowledge/mcp/server'
5966
import {
6067
LIVE_DATE_ORDER_MESSAGE,
@@ -544,3 +551,58 @@ describe('MCP tool completion records', () => {
544551
)
545552
})
546553
})
554+
555+
describe('people lookup', () => {
556+
const person = (memberId: string, name: string, title: string | null) => ({
557+
memberId,
558+
userId: null,
559+
name,
560+
email: `${memberId}@example.test`,
561+
image: null,
562+
title,
563+
department: null,
564+
location: null,
565+
startDate: null,
566+
manager: null,
567+
managerMemberId: null,
568+
directorySource: null,
569+
joinedAt: null,
570+
})
571+
async function lookUp(input: Record<string, unknown>) {
572+
createKnowledgeMcpServer({ organizationId: 'org-1', request, auth, searchPeople: true })
573+
const [part] = (await call('search_people', input)).content
574+
if (part?.type !== 'text') throw new Error('Expected text content')
575+
return JSON.parse(part.text) as Record<string, unknown>
576+
}
577+
578+
it('answers a query that finds one person with their reporting line in the same call', async () => {
579+
mocks.listPeople.mockResolvedValueOnce({
580+
data: [person('report', 'Ada Report', 'Engineer')],
581+
nextCursorKeys: null,
582+
})
583+
mocks.getPerson.mockResolvedValueOnce({
584+
person: person('report', 'Ada Report', 'Engineer'),
585+
chain: [person('lead', 'Grace Lead', 'Director')],
586+
reports: [],
587+
totalReports: 0,
588+
})
589+
expect(await lookUp({ query: 'ada' })).toEqual({
590+
person: {
591+
personId: 'report',
592+
name: 'Ada Report',
593+
title: 'Engineer',
594+
email: 'report@example.test',
595+
managerChain: [{ personId: 'lead', name: 'Grace Lead', title: 'Director' }],
596+
totalDirectReports: 0,
597+
},
598+
})
599+
})
600+
601+
it('points a query that matches no one at search for people outside the organization', async () => {
602+
mocks.listPeople.mockResolvedValueOnce({ data: [], nextCursorKeys: null })
603+
expect(await lookUp({ query: 'outside contact' })).toEqual({
604+
people: [],
605+
note: NO_PEOPLE_MATCH_NOTE,
606+
})
607+
})
608+
})

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

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import {
2222
recordOrganizationSearchMcpActivity,
2323
type SearchMcpActivityInput,
2424
} from '@/lib/knowledge/mcp/activity'
25+
import { registerSearchPeopleTool } from '@/lib/knowledge/mcp/people'
2526
import { shareReadBudget } from '@/lib/knowledge/mcp/read-budget'
2627
import {
2728
KNOWLEDGE_MCP_READ_ONLY,
@@ -158,6 +159,8 @@ interface KnowledgeMcpContext {
158159
organizationId: string
159160
request: NextRequest
160161
auth: V2ApiKeyAuthContext
162+
/** Registers search_people, which its use cases authorize on every call. */
163+
searchPeople?: boolean
161164
}
162165

163166
/** A request owns its server; no credential or principal survives into another HTTP request. */
@@ -361,5 +364,8 @@ export function createKnowledgeMcpServer(context: KnowledgeMcpContext): McpServe
361364
})
362365
)
363366

367+
if (context.searchPeople)
368+
registerSearchPeopleTool(server, { execute, principal, organizationId, request })
369+
364370
return server
365371
}

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import {
44
chatSearchMcpSchema,
55
liveSearchMcpSchema,
66
readLiveDocumentMcpSchema,
7+
searchPeopleMcpSchema,
78
} from '@/lib/api/contracts/knowledge/mcp'
89
import { mcpToolCallParamsSchema } from '@/lib/api/contracts/mcp'
910
import { liveSearchProviderSchema } from '@/lib/api/contracts/mothership-assistant-tools'
@@ -23,6 +24,7 @@ const TOOL_INPUT_SCHEMAS = new Map<string, z.ZodType>([
2324
['search', liveSearchMcpSchema],
2425
['read_document', readLiveDocumentMcpSchema],
2526
['chat', chatSearchMcpSchema],
27+
['search_people', searchPeopleMcpSchema],
2628
])
2729

2830
function readToolCall(message: Record<string, unknown>) {

0 commit comments

Comments
 (0)