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
41 changes: 1 addition & 40 deletions apps/sim/lib/api/contracts/knowledge/mcp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,6 @@ 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 @@ -58,9 +53,7 @@ export const liveSearchMcpSchema = searchWorkspaceInputFieldsSchema
...mcpDateFilterFields,
involving: liveSearchInvolvingSchema
.optional()
.describe(
'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.'
),
.describe(searchWorkspaceInputFieldsSchema.shape.involving.description ?? ''),
topK: searchWorkspaceInputFieldsSchema.shape.topK
.unwrap()
.optional()
Expand Down Expand Up @@ -138,35 +131,3 @@ 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
.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.',
})
52 changes: 52 additions & 0 deletions apps/sim/lib/api/contracts/mothership-assistant-tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,15 @@ export const searchWorkspaceInputFieldsSchema = workspaceSearchFiltersSchema.ext
.describe(
'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.'
),
involving: z
.string()
.trim()
.min(1)
.max(254)
.optional()
.describe(
'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.'
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
),
topK: z
.number()
.int()
Expand Down Expand Up @@ -323,6 +332,42 @@ export const readDocumentInputSchema = z.object({
),
})

/**
* Organization directory lookups. The bounds mirror the People page's search limits
* (`lib/people/validation`) as literals, so the worker's generated copy stays standalone.
*/
export const searchPeopleInputSchema = z
.object({
query: z
.string()
.trim()
.min(1)
.max(200)
.optional()
.describe(
'Up to 8 words from a name, email, title, department, or location; a person matches when every word appears in one of them.'
),
personId: z
.string()
.min(1)
.max(255)
.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.',
})

/** Connection requests name a provider and optionally an owned account to repair. */
export const oauthGetAuthLinkInputSchema = z.object({
providerName: z
Expand Down Expand Up @@ -386,6 +431,13 @@ export const assistantToolContracts = [
description: 'Read more context from an accessible connected-source document.',
inputSchema: readDocumentInputSchema,
},
{
id: 'search_people',
route: 'sim',
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_workspace for customers, vendors, and other outside contacts.',
inputSchema: searchPeopleInputSchema,
},
{
id: 'oauth_get_auth_link',
route: 'sim',
Expand Down
129 changes: 10 additions & 119 deletions apps/sim/lib/knowledge/mcp/people.ts
Original file line number Diff line number Diff line change
@@ -1,81 +1,14 @@
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 { searchPeopleInputSchema } from '@/lib/api/contracts/mothership-assistant-tools'
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 } : {}),
}
}
import { findDirectoryPeople, readDirectoryPerson } from '@/lib/people/directory-lookup'

interface SearchPeopleToolContext {
execute: KnowledgeMcpToolRunner
Expand All @@ -93,70 +26,28 @@ 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,
...(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,
inputSchema: searchPeopleInputSchema,
annotations: KNOWLEDGE_MCP_READ_ONLY,
},
async (input: unknown, extra: { signal: AbortSignal }) => {
const personId = searchPeopleMcpSchema.safeParse(input).data?.personId
const personId = searchPeopleInputSchema.safeParse(input).data?.personId
if (personId)
return execute('search_people', getPerson.operation, extra.signal, async (registry) =>
projectResult(await detail(personId), registry)
projectResult(
await readDirectoryPerson({ principal, organizationId, request, 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)
const { query, cursor } = searchPeopleInputSchema.parse(input)
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 }),
},
await findDirectoryPeople({ principal, organizationId, request, query, cursor }),
registry
)
})
Expand Down
4 changes: 2 additions & 2 deletions apps/sim/lib/knowledge/mcp/route-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,10 @@ 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 { canLookUpPeople } from '@/lib/people/directory-lookup'
import { v2CaughtOrchestrationError, v2Error } from '@/app/api/v2/lib/response'

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

function mcpAuth(resource: string) {
Expand Down
2 changes: 1 addition & 1 deletion apps/sim/lib/knowledge/mcp/server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,8 @@ 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 { NO_PEOPLE_MATCH_NOTE } from '@/lib/people/directory-lookup'
import {
LIVE_DATE_ORDER_MESSAGE,
LIVE_MORE_RANKED_BELOW_MESSAGE,
Expand Down
8 changes: 5 additions & 3 deletions apps/sim/lib/knowledge/mcp/tool-arguments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@ 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'
import {
liveSearchProviderSchema,
searchPeopleInputSchema,
} from '@/lib/api/contracts/mothership-assistant-tools'

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

function readToolCall(message: Record<string, unknown>) {
Expand Down
42 changes: 42 additions & 0 deletions apps/sim/lib/mothership/application/execute-people-use-case.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import type { OrganizationDelegatedPrincipal } from '@sim/auth/principal'
import { OrchestrationError } from '@/lib/core/orchestration/types'
import {
COPILOT_APPLICATION_DELEGATION_TTL_MS,
type CopilotExecutionContext,
createTrustedOrganizationCopilotPrincipal,
requireTrustedOrganizationCopilotContext,
} from '@/lib/mothership/auth/application-delegation'
import { authorizeOrganizationChatDelegation } from '@/lib/mothership/chat/organization-chats'
import { peopleOperations } from '@/lib/people/application/operations'

interface CopilotPeopleScope {
principal: OrganizationDelegatedPrincipal
organizationId: string
}

/**
* Runs a People directory read for the organization Assistant, the only mode Sim grants the
* `people` entitlement in. The subject and organization come from the trusted turn, the
* delegation is bound to the member's private chat, and the People use cases the read calls
* still check the feature, the membership and the directory capability.
*/
export async function executeCopilotPeopleRead<R>(
context: CopilotExecutionContext | undefined,
read: (scope: CopilotPeopleScope) => Promise<R>
): Promise<R> {
const trusted = requireTrustedOrganizationCopilotContext(context)
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
if (context?.requestMode !== 'assistant')
throw new OrchestrationError(
'forbidden',
'The People directory is available only in organization Assistant conversations'
)
const principal = createTrustedOrganizationCopilotPrincipal(
{ ...trusted, delegationId: trusted.toolCallId },
{
audience: peopleOperations.list.delegationAudience,
ttlMs: COPILOT_APPLICATION_DELEGATION_TTL_MS,
}
)
await authorizeOrganizationChatDelegation.execute({ principal })
return read({ principal, organizationId: trusted.organizationId })
}
Loading
Loading