Skip to content

Commit d324564

Browse files
committed
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.
1 parent 2fbc5f3 commit d324564

14 files changed

Lines changed: 34369 additions & 14 deletions

File tree

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

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ 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 { PEOPLE_ID_MAX_LENGTH, PEOPLE_SEARCH_MAX_LENGTH } from '@/lib/people/validation'
1112

1213
export const organizationKnowledgeMcpContract = defineRouteContract({
1314
method: 'POST',
@@ -115,3 +116,31 @@ export const chatSearchMcpSchema = workspaceSearchFiltersSchema
115116
query: z.string().trim().min(1, 'A question is required').max(8192),
116117
})
117118
.strict()
119+
120+
export const searchPeopleMcpSchema = z
121+
.object({
122+
query: z
123+
.string()
124+
.trim()
125+
.min(1)
126+
.max(PEOPLE_SEARCH_MAX_LENGTH)
127+
.optional()
128+
.describe(
129+
'Words from a name, email, title, department, or location; a person matches when every word appears in one of them.'
130+
),
131+
personId: z
132+
.string()
133+
.min(1)
134+
.max(PEOPLE_ID_MAX_LENGTH)
135+
.optional()
136+
.describe(
137+
'A personId from an earlier result, to show that person with their managers and direct reports. Used instead of query.'
138+
),
139+
cursor: z
140+
.string()
141+
.min(1)
142+
.max(1024)
143+
.optional()
144+
.describe('nextCursor from the previous page of the same query.'),
145+
})
146+
.strict()

‎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: 160 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,160 @@
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+
...(report.reportCount ? { 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+
},
109+
}
110+
}
111+
112+
server.registerTool(
113+
'search_people',
114+
{
115+
title: 'Search people',
116+
description:
117+
'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.',
118+
inputSchema: searchPeopleMcpSchema,
119+
annotations: KNOWLEDGE_MCP_READ_ONLY,
120+
},
121+
async (input: unknown, extra: { signal: AbortSignal }) => {
122+
const personId = searchPeopleMcpSchema.safeParse(input).data?.personId
123+
if (personId)
124+
return execute('search_people', getPerson.operation, extra.signal, async (registry) =>
125+
projectResult(await detail(personId), registry)
126+
)
127+
return execute('search_people', listPeople.operation, extra.signal, async (registry) => {
128+
const { query, cursor } = searchPeopleMcpSchema.parse(input)
129+
const scope = cursorScopeKey(
130+
cursorRoute(organizationKnowledgeMcpContract, { organizationId }),
131+
{ tool: 'search_people', query }
132+
)
133+
const page = await listPeople.execute({
134+
principal,
135+
input: {
136+
organizationId,
137+
search: query,
138+
cursorKeys: readSortedCursor(cursor, 'name', 'asc', scope),
139+
},
140+
request,
141+
})
142+
const [only] = page.data
143+
if (only && page.data.length === 1 && !cursor)
144+
return projectResult(await detail(only.memberId), registry)
145+
const nextCursor = writeSortedCursor(page.nextCursorKeys, 'name', 'asc', scope)
146+
return projectResult(
147+
{
148+
people: page.data.map((person) => ({
149+
...personFacts(person),
150+
...(person.manager ? { manager: person.manager.name } : {}),
151+
})),
152+
...(nextCursor ? { nextCursor } : {}),
153+
...(page.data.length ? {} : { note: NO_PEOPLE_MATCH_NOTE }),
154+
},
155+
registry
156+
)
157+
})
158+
}
159+
)
160+
}

‎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)