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
37 changes: 37 additions & 0 deletions apps/sim/lib/api/contracts/knowledge/mcp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ import {
} from '@/lib/api/contracts/mothership-assistant-tools'
import { organizationIdSchema } from '@/lib/api/contracts/primitives'
import { defineRouteContract } from '@/lib/api/contracts/types'
import {
PEOPLE_ID_MAX_LENGTH,
PEOPLE_SEARCH_MAX_LENGTH,
PEOPLE_SEARCH_MAX_TERMS,
} from '@/lib/people/validation'

export const organizationKnowledgeMcpContract = defineRouteContract({
method: 'POST',
Expand Down Expand Up @@ -125,3 +130,35 @@ export const chatSearchMcpSchema = workspaceSearchFiltersSchema
.describe('The chatId of an earlier chat answer, to ask a follow-up in that conversation.'),
})
.strict()

export const searchPeopleMcpSchema = z
.object({
query: z
.string()
.trim()
.min(1)
.max(PEOPLE_SEARCH_MAX_LENGTH)
.optional()
.describe(
`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.`
),
personId: z
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
.string()
.min(1)
.max(PEOPLE_ID_MAX_LENGTH)
.optional()
.describe(
'A personId from an earlier result, to show that person with their managers and direct reports. Used instead of query.'
),
cursor: z
.string()
.min(1)
.max(1024)
.optional()
.describe('nextCursor from the previous page of the same query.'),
})
.strict()
.refine((input) => !input.personId || (input.query === undefined && !input.cursor), {
path: ['personId'],
message: 'Pass either personId or a query with its cursor, not both.',
})
2 changes: 1 addition & 1 deletion apps/sim/lib/auth/oauth-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ export const OAUTH_SCOPE_DESCRIPTIONS: Record<OAuthScope, string> = {
[OAUTH_API_READ_SCOPE]: 'Read your workspaces, workflows, files, tables, and logs',
[OAUTH_API_WRITE_SCOPE]: 'Read, create, change, run, and delete resources in your workspaces',
[OAUTH_SEARCH_READ_SCOPE]:
'Search and read documents you can access, and start private Sim Search conversations',
'Search and read documents you can access, look up people in your organization, and start private Sim Search conversations',
}

/**
Expand Down
165 changes: 165 additions & 0 deletions apps/sim/lib/knowledge/mcp/people.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import type { Principal } from '@sim/auth/principal'
import { createLogger } from '@sim/logger'
import { getErrorMessage } from '@sim/utils/errors'
import type { NextRequest } from 'next/server'
import {
organizationKnowledgeMcpContract,
searchPeopleMcpSchema,
} from '@/lib/api/contracts/knowledge/mcp'
import type { PersonSummary } from '@/lib/api/contracts/people'
import { cursorRoute, cursorScopeKey } from '@/lib/api/cursor-binding'
import { OrchestrationError } from '@/lib/core/orchestration/types'
import {
KNOWLEDGE_MCP_READ_ONLY,
type KnowledgeMcpToolRunner,
projectResult,
} from '@/lib/knowledge/mcp/tool-runner'
import { getPerson, listPeople } from '@/lib/people/application/use-cases'
import { isPeopleEnabled } from '@/lib/people/feature-flag'
import type { PersonRecord } from '@/lib/people/repository'
import { readSortedCursor, writeSortedCursor } from '@/app/api/v2/lib/response'

const logger = createLogger('KnowledgeMcpPeople')

/** Said when a query matches no one, so a client looks for people outside the organization in search. */
export const NO_PEOPLE_MATCH_NOTE =
'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.'

/**
* Whether `principal` may look people up in `organizationId`: People is on there and the
* directory is open to them. Asked when listing tools, so a client whose organization has no
* People directory, or who may not browse it, is never offered the tool. A lookup that fails hides
* the tool rather than failing the listing around it.
*/
export async function canSearchPeople(
principal: Principal,
organizationId: string
): Promise<boolean> {
try {
if (!(await isPeopleEnabled(organizationId))) return false
await listPeople.authorize({ principal, input: { organizationId } })
return true
} catch (error) {
if (!(error instanceof OrchestrationError))
logger.warn('Could not resolve Search MCP people access', {
organizationId,
error: getErrorMessage(error),
})
return false
}
}

function summaryFacts(person: PersonSummary) {
return {
personId: person.memberId,
name: person.name,
...(person.title ? { title: person.title } : {}),
}
}

function reportFacts(report: PersonSummary & { department: string | null; reportCount: number }) {
return {
...summaryFacts(report),
...(report.department ? { department: report.department } : {}),
directReports: report.reportCount,
}
}

function personFacts(person: PersonRecord) {
const { department, location, startDate } = person
return {
...summaryFacts(person),
email: person.email,
...(department ? { department } : {}),
...(location ? { location } : {}),
...(startDate ? { startDate } : {}),
}
}

interface SearchPeopleToolContext {
execute: KnowledgeMcpToolRunner
principal: Principal
organizationId: string
request: NextRequest
}

/**
* Registers `search_people`: the organization's People directory through the same use cases the
* People page reads. A query that finds one person, or a personId, returns that person with their
* reporting line, so "who is X's manager" or "who reports to X" takes one call.
*/
export function registerSearchPeopleTool(
server: McpServer,
{ execute, principal, organizationId, request }: SearchPeopleToolContext
) {
const detail = async (memberId: string) => {
const { person, chain, reports, totalReports } = await getPerson.execute({
principal,
input: { organizationId, memberId },
request,
})
return {
person: {
...personFacts(person),
...(chain.length ? { managerChain: chain.map(summaryFacts) } : {}),
...(reports.length ? { directReports: reports.map(reportFacts) } : {}),
totalDirectReports: totalReports,
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
...(totalReports > reports.length
? {
note: `directReports lists the first ${reports.length} of ${totalReports}; search by department or title to find the others.`,
}
: {}),
},
}
}

server.registerTool(
'search_people',
{
title: 'Search people',
description:
'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.',
inputSchema: searchPeopleMcpSchema,
annotations: KNOWLEDGE_MCP_READ_ONLY,
},
async (input: unknown, extra: { signal: AbortSignal }) => {
const personId = searchPeopleMcpSchema.safeParse(input).data?.personId
if (personId)
return execute('search_people', getPerson.operation, extra.signal, async (registry) =>
projectResult(await detail(personId), registry)
)
return execute('search_people', listPeople.operation, extra.signal, async (registry) => {
const { query, cursor } = searchPeopleMcpSchema.parse(input)
const scope = cursorScopeKey(
cursorRoute(organizationKnowledgeMcpContract, { organizationId }),
{ tool: 'search_people', query }
)
const page = await listPeople.execute({
principal,
input: {
organizationId,
search: query,
cursorKeys: readSortedCursor(cursor, 'name', 'asc', scope),
},
request,
})
const [only] = page.data
if (only && page.data.length === 1 && !cursor)
return projectResult(await detail(only.memberId), registry)
const nextCursor = writeSortedCursor(page.nextCursorKeys, 'name', 'asc', scope)
return projectResult(
{
people: page.data.map((person) => ({
...personFacts(person),
...(person.manager ? { manager: person.manager.name } : {}),
})),
...(nextCursor ? { nextCursor } : {}),
...(page.data.length ? {} : { note: NO_PEOPLE_MATCH_NOTE }),
},
registry
)
})
}
)
}
18 changes: 18 additions & 0 deletions apps/sim/lib/knowledge/mcp/route-handler.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import type { Principal } from '@sim/auth/principal'
import { createLogger } from '@sim/logger'
import { isRecordLike } from '@sim/utils/object'
import type { NextRequest } from 'next/server'
import { organizationKnowledgeMcpContract } from '@/lib/api/contracts/knowledge/mcp'
import { parseRequest } from '@/lib/api/server'
Expand All @@ -13,13 +15,28 @@ import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import { knowledgeOperations } from '@/lib/knowledge/application/operations'
import { readSearchIndex } from '@/lib/knowledge/application/sim-search'
import { withSearchMcpAuthChallenge } from '@/lib/knowledge/mcp/oauth-metadata'
import { canSearchPeople } from '@/lib/knowledge/mcp/people'
import { createKnowledgeMcpServer } from '@/lib/knowledge/mcp/server'
import { repairToolCallMessage, toolCallInputIssues } from '@/lib/knowledge/mcp/tool-arguments'
import { getSearchMcpUrl } from '@/lib/knowledge/mcp/urls'
import { v2CaughtOrchestrationError, v2Error } from '@/app/api/v2/lib/response'

const logger = createLogger('KnowledgeMcp')

/**
* Whether this message needs search_people registered. A call to it is authorized by its own use
* cases, so only a tools/list asks whether the caller may browse People, and other messages skip it.
*/
async function offersSearchPeople(
message: Record<string, unknown>,
principal: Principal,
organizationId: string
) {
if (message.method === 'tools/call')
return isRecordLike(message.params) && message.params.name === 'search_people'
return message.method === 'tools/list' && canSearchPeople(principal, organizationId)
}

function mcpAuth(resource: string) {
return mcpCredentialAuth({ resource, allowUnboundApiTokens: true })
}
Expand Down Expand Up @@ -62,6 +79,7 @@ export function createKnowledgeMcpHandlers() {
request,
auth: admission.auth,
...parsed.data.params,
searchPeople: await offersSearchPeople(message, admission.auth.principal, organizationId),
})
return await serveStatelessMcp(server, request, message)
} catch (error) {
Expand Down
62 changes: 62 additions & 0 deletions apps/sim/lib/knowledge/mcp/server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,12 @@ const hoisted = vi.hoisted(() => ({
rateLimit: vi.fn(),
afterResponse: vi.fn<(task: () => Promise<void>) => void>(),
recordActivity: vi.fn(),
listPeople: vi.fn(),
getPerson: vi.fn(),
}))
vi.mock('@/lib/people/application/use-cases', () => ({
listPeople: { operation: { id: 'organization.people.list' }, execute: hoisted.listPeople },
getPerson: { execute: hoisted.getPerson },
}))
vi.mock('@/lib/core/utils/after-response', () => ({ afterResponse: hoisted.afterResponse }))
vi.mock('@/lib/knowledge/mcp/activity', () => ({
Expand Down Expand Up @@ -55,6 +61,7 @@ vi.mock('@/lib/knowledge/application/chat', () => ({
}))

import { OrchestrationError } from '@/lib/core/orchestration/types'
import { NO_PEOPLE_MATCH_NOTE } from '@/lib/knowledge/mcp/people'
import { createKnowledgeMcpServer } from '@/lib/knowledge/mcp/server'
import {
LIVE_DATE_ORDER_MESSAGE,
Expand Down Expand Up @@ -544,3 +551,58 @@ describe('MCP tool completion records', () => {
)
})
})

describe('people lookup', () => {
const person = (memberId: string, name: string, title: string | null) => ({
memberId,
userId: null,
name,
email: `${memberId}@example.test`,
image: null,
title,
department: null,
location: null,
startDate: null,
manager: null,
managerMemberId: null,
directorySource: null,
joinedAt: null,
})
async function lookUp(input: Record<string, unknown>) {
createKnowledgeMcpServer({ organizationId: 'org-1', request, auth, searchPeople: true })
const [part] = (await call('search_people', input)).content
if (part?.type !== 'text') throw new Error('Expected text content')
return JSON.parse(part.text) as Record<string, unknown>
}

it('answers a query that finds one person with their reporting line in the same call', async () => {
mocks.listPeople.mockResolvedValueOnce({
data: [person('report', 'Ada Report', 'Engineer')],
nextCursorKeys: null,
})
mocks.getPerson.mockResolvedValueOnce({
person: person('report', 'Ada Report', 'Engineer'),
chain: [person('lead', 'Grace Lead', 'Director')],
reports: [],
totalReports: 0,
})
expect(await lookUp({ query: 'ada' })).toEqual({
person: {
personId: 'report',
name: 'Ada Report',
title: 'Engineer',
email: 'report@example.test',
managerChain: [{ personId: 'lead', name: 'Grace Lead', title: 'Director' }],
totalDirectReports: 0,
},
})
})

it('points a query that matches no one at search for people outside the organization', async () => {
mocks.listPeople.mockResolvedValueOnce({ data: [], nextCursorKeys: null })
expect(await lookUp({ query: 'outside contact' })).toEqual({
people: [],
note: NO_PEOPLE_MATCH_NOTE,
})
})
})
6 changes: 6 additions & 0 deletions apps/sim/lib/knowledge/mcp/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {
recordOrganizationSearchMcpActivity,
type SearchMcpActivityInput,
} from '@/lib/knowledge/mcp/activity'
import { registerSearchPeopleTool } from '@/lib/knowledge/mcp/people'
import { shareReadBudget } from '@/lib/knowledge/mcp/read-budget'
import {
KNOWLEDGE_MCP_READ_ONLY,
Expand Down Expand Up @@ -158,6 +159,8 @@ interface KnowledgeMcpContext {
organizationId: string
request: NextRequest
auth: V2ApiKeyAuthContext
/** Registers search_people, which its use cases authorize on every call. */
searchPeople?: boolean
}

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

if (context.searchPeople)
registerSearchPeopleTool(server, { execute, principal, organizationId, request })

return server
}
2 changes: 2 additions & 0 deletions apps/sim/lib/knowledge/mcp/tool-arguments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
chatSearchMcpSchema,
liveSearchMcpSchema,
readLiveDocumentMcpSchema,
searchPeopleMcpSchema,
} from '@/lib/api/contracts/knowledge/mcp'
import { mcpToolCallParamsSchema } from '@/lib/api/contracts/mcp'
import { liveSearchProviderSchema } from '@/lib/api/contracts/mothership-assistant-tools'
Expand All @@ -23,6 +24,7 @@ const TOOL_INPUT_SCHEMAS = new Map<string, z.ZodType>([
['search', liveSearchMcpSchema],
['read_document', readLiveDocumentMcpSchema],
['chat', chatSearchMcpSchema],
['search_people', searchPeopleMcpSchema],
])

function readToolCall(message: Record<string, unknown>) {
Expand Down
Loading
Loading