|
| 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 | +} |
0 commit comments