Skip to content

Commit 17f371b

Browse files
authored
feat(search-mcp): involving person filter on live search (#10439)
* feat(search-mcp): involving person filter on live search Adds an optional involving field ("me" or an email) to the Search MCP search tool. Each provider that can filter by person applies its own native clause; sources that cannot are skipped with an unavailable status instead of returning unfiltered results. * fix(search-mcp): match calendar person by account email, resolve Jira people across sites, skip Confluence for colleague emails * fix(search-mcp): continue a person-filtered calendar search on the primary calendar * improvement(search-mcp): steer involving to emails and activity questions * fix(search-mcp): never take a Jira user showing another address as the person
1 parent 39b871b commit 17f371b

15 files changed

Lines changed: 455 additions & 44 deletions

File tree

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

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
import { z } from 'zod'
2-
import { workspaceSearchFiltersSchema } from '@/lib/api/contracts/knowledge/search'
2+
import {
3+
liveSearchInvolvingSchema,
4+
workspaceSearchFiltersSchema,
5+
} from '@/lib/api/contracts/knowledge/search'
36
import { mcpJsonRpcMessageSchema } from '@/lib/api/contracts/mcp'
47
import {
58
readDocumentInputSchema,
@@ -53,6 +56,11 @@ const mcpDateFilterFields = {
5356
export const liveSearchMcpSchema = searchWorkspaceInputFieldsSchema
5457
.extend({
5558
...mcpDateFilterFields,
59+
involving: liveSearchInvolvingSchema
60+
.optional()
61+
.describe(
62+
'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.'
63+
),
5664
topK: searchWorkspaceInputFieldsSchema.shape.topK
5765
.unwrap()
5866
.optional()

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

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { isValidEmailSyntax, normalizeEmail } from '@sim/utils/string'
12
import { z } from 'zod'
23
import {
34
nativeSearchQueriesSchema,
@@ -182,6 +183,18 @@ export { workspaceSearchFiltersSchema }
182183

183184
export type WorkspaceSearchFilters = z.output<typeof workspaceSearchFiltersSchema>
184185

186+
/**
187+
* The person a live search is limited to: `me` or a normalized email. Checked by refinement
188+
* rather than `z.email()` so a tools/list schema built from it carries no long email pattern.
189+
*/
190+
export const liveSearchInvolvingSchema = z
191+
.string()
192+
.transform(normalizeEmail)
193+
.refine((value) => value === 'me' || isValidEmailSyntax(value), {
194+
message:
195+
'involving takes "me" or an email address, not a name. Find the person\'s email first, or search without involving.',
196+
})
197+
185198
/** Chunks a search asks for at first paint, and once the reader asks for more; both within `topK`'s bound. */
186199
export const WORKSPACE_KNOWLEDGE_SEARCH_LIMITS = { initial: 20, expanded: 50 } as const
187200
export type WorkspaceKnowledgeSearchLimit =

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

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ import { toolError } from '@/lib/mcp/tool-result'
3333
import {
3434
LIVE_DATE_ORDER_MESSAGE,
3535
LIVE_MORE_RANKED_BELOW_MESSAGE,
36+
LIVE_NO_PERSON_FILTER_MESSAGE,
3637
LIVE_NOT_STARTED_MESSAGE,
3738
LIVE_OVER_ACCOUNT_LIMIT_MESSAGE,
3839
readLiveDocument,
@@ -93,6 +94,7 @@ const LIVE_ACCOUNT_NOTES = {
9394
dateOrderPartial: LIVE_DATE_ORDER_MESSAGE,
9495
notSearchedByDeadline: LIVE_NOT_STARTED_MESSAGE,
9596
notSearchedOverLimit: LIVE_OVER_ACCOUNT_LIMIT_MESSAGE,
97+
notFilteredByPerson: LIVE_NO_PERSON_FILTER_MESSAGE,
9698
}
9799

98100
/**
@@ -237,7 +239,7 @@ export function createKnowledgeMcpServer(context: KnowledgeMcpContext): McpServe
237239
async (input: unknown, extra: { signal: AbortSignal }) =>
238240
execute('search', knowledgeOperations.search, extra.signal, async (registry, signal) => {
239241
const parsed = liveSearchMcpSchema.parse(input)
240-
const { query, topK, nativeQueries, ...filters } = parsed
242+
const { query, topK, nativeQueries, involving, ...filters } = parsed
241243
const result = await searchLiveKnowledge.execute({
242244
principal,
243245
input: {
@@ -246,6 +248,7 @@ export function createKnowledgeMcpServer(context: KnowledgeMcpContext): McpServe
246248
query,
247249
topK: topK ?? liveSearchMcpDefaultTopK(parsed),
248250
nativeQueries,
251+
involving,
249252
filters,
250253
resultSecretRegistry: registry,
251254
signal,

‎apps/sim/lib/knowledge/search/diagnostics.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,8 @@ export interface SearchDiagnosticMetadata {
7878
documentFilterCount?: number
7979
hasSourceFilter?: boolean
8080
hasDateFilter?: boolean
81+
/** Whether a live search was limited to the caller (`me`) or another person; never the email. */
82+
involving?: 'me' | 'person'
8183
tagFilterCount?: number
8284
hasProvenance?: boolean
8385
searchMode?: 'hybrid' | 'vector'
@@ -157,11 +159,13 @@ export function describeSearchRequest(input: {
157159
query: string
158160
filters?: WorkspaceSearchFilters
159161
nativeQueries?: readonly NativeSearchQuery[]
162+
involving?: string
160163
}): SearchDiagnosticMetadata {
161164
const { start, end } = nativeDateBounds({ filters: input.filters })
162165
return {
163166
queryTermCount: input.query.split(/\s+/).filter(Boolean).length,
164167
sortBy: input.filters?.sortBy,
168+
...(input.involving ? { involving: input.involving === 'me' ? 'me' : 'person' } : {}),
165169
...(start && end
166170
? { dateWindowDays: Math.round(((Date.parse(end) - Date.parse(start)) / DAY_MS) * 10) / 10 }
167171
: {}),

‎apps/sim/lib/sim-search/live/application.test.ts‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ vi.mock('@/lib/sim-search/live/accounts', () => ({
6666
}),
6767
}))
6868
vi.mock('@/lib/sim-search/live/providers', () => ({
69+
filtersByPerson: (provider: string) => provider !== 'notion',
6970
liveSearchGuidance: (providers: string[]) => `Live coverage: ${[...new Set(providers)]}`,
7071
searchNativeProvider: mocks.search,
7172
readNativeProvider: mocks.read,
@@ -1061,6 +1062,47 @@ describe('authorized live retrieval', () => {
10611062
})
10621063
expect(mocks.resolveAccount).not.toHaveBeenCalled()
10631064
})
1065+
describe('person filter', () => {
1066+
const notion = {
1067+
...account,
1068+
id: 'notion-account',
1069+
provider: 'notion' as const,
1070+
providerId: 'mcp:notion',
1071+
type: 'managed_mcp' as const,
1072+
displayName: 'Notion',
1073+
}
1074+
it('never searches a source that cannot filter by person, so no result is unfiltered', async () => {
1075+
mocks.accounts.mockResolvedValue([account, notion])
1076+
const result = await searchLiveKnowledge.execute({
1077+
principal,
1078+
input: { ...input, involving: 'jane@example.com' },
1079+
})
1080+
expect(mocks.resolveAccount).toHaveBeenCalledTimes(1)
1081+
expect(mocks.mcpCall).not.toHaveBeenCalled()
1082+
expect(result.live?.accounts).toContainEqual(
1083+
expect.objectContaining({
1084+
accountId: 'notion-account',
1085+
status: 'unavailable',
1086+
message: expect.stringContaining('cannot filter by this person'),
1087+
})
1088+
)
1089+
expect(result.live?.guidance).toBe('Live coverage: google_drive')
1090+
expect(result.retrieval.status).toBe('partial')
1091+
})
1092+
it('hands each provider search the normalized person', async () => {
1093+
await searchLiveKnowledge.execute({
1094+
principal,
1095+
input: { ...input, involving: ' Jane@Example.com ' },
1096+
})
1097+
expect(mocks.search.mock.calls[0]?.[2]).toMatchObject({ involving: 'jane@example.com' })
1098+
})
1099+
it('rejects a person that is neither me nor an email before any account is opened', async () => {
1100+
await expect(
1101+
searchLiveKnowledge.execute({ principal, input: { ...input, involving: 'Jane Doe' } })
1102+
).rejects.toThrow()
1103+
expect(mocks.resolveAccount).not.toHaveBeenCalled()
1104+
})
1105+
})
10641106
it('rechecks revoked account access on every document read', async () => {
10651107
const search = await searchLiveKnowledge.execute({ principal, input })
10661108
mocks.resolveAccount.mockRejectedValue(new NativeSearchError('reconnect', 'Revoked'))

‎apps/sim/lib/sim-search/live/application.ts‎

Lines changed: 45 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import { canonicalJson } from '@sim/utils/object'
77
import { compareStrings } from '@sim/utils/string'
88
import { z } from 'zod'
99
import type { WorkspaceSearchFilters } from '@/lib/api/contracts/knowledge'
10+
import { liveSearchInvolvingSchema } from '@/lib/api/contracts/knowledge/search'
1011
import type {
1112
WorkspaceKnowledgeSearchData,
1213
WorkspaceKnowledgeSearchResult,
@@ -82,7 +83,7 @@ import { isManagedSearchMcpProvider } from '@/lib/sim-search/live/managed-mcp-co
8283
import { joinMessages } from '@/lib/sim-search/live/pages'
8384
import { loadLiveSearchPolicies } from '@/lib/sim-search/live/policy-store'
8485
import { LIVE_SEARCH_PROVIDER_IDS } from '@/lib/sim-search/live/provider-catalog'
85-
import { liveSearchGuidance } from '@/lib/sim-search/live/providers'
86+
import { filtersByPerson, liveSearchGuidance } from '@/lib/sim-search/live/providers'
8687
import { LiveReadError } from '@/lib/sim-search/live/read-error'
8788
import { encodedWindowEnd, READ_WINDOW_CHARACTERS } from '@/lib/sim-search/live/read-window'
8889
import {
@@ -162,6 +163,8 @@ interface LiveSearchOptions {
162163
topK: number
163164
filters?: WorkspaceSearchFilters
164165
nativeQueries?: NativeSearchQuery[]
166+
/** Only items this person took part in: `me` or another person's lowercase email. */
167+
involving?: string
165168
signal?: AbortSignal
166169
resultSecretRegistry?: ResolvedSecretTraceRegistry
167170
}
@@ -295,6 +298,9 @@ export const LIVE_NOT_STARTED_MESSAGE =
295298
'Not searched before the search deadline. Search this account alone or narrow the query.'
296299
/** Account status for each eligible account beyond {@link MAX_ACCOUNTS}. */
297300
export const LIVE_OVER_ACCOUNT_LIMIT_MESSAGE = `Not searched: one search covers at most ${MAX_ACCOUNTS} accounts. Search this source or account alone.`
301+
/** Account status when a search filtered by person reaches a provider that cannot apply it. */
302+
export const LIVE_NO_PERSON_FILTER_MESSAGE =
303+
'Not searched: this source cannot filter by this person. Search it without involving.'
298304
/** Previews center on the query's longest matching term, like indexed passages. */
299305
const PREVIEW_CHARACTERS = 1800
300306
/**
@@ -486,14 +492,23 @@ const liveKnowledgeSearch = defineAuthorizedKnowledgeUseCase({
486492
const requestedFilters = input.filters
487493
? workspaceSearchFiltersSchema.parse(input.filters)
488494
: undefined
489-
input = { ...input, filters: requestedFilters }
495+
input = {
496+
...input,
497+
filters: requestedFilters,
498+
involving: liveSearchInvolvingSchema.optional().parse(input.involving),
499+
}
490500
if (
491501
(!input.query.trim() && !queries?.some((query) => query.query)) ||
492502
queries?.some((query) => !query.query)
493503
)
494504
input = { ...input, filters: withImpliedListingBound(input.filters, new Date()) }
495505
annotateSearchDiagnostics(
496-
describeSearchRequest({ query: input.query, filters: input.filters, nativeQueries: queries })
506+
describeSearchRequest({
507+
query: input.query,
508+
filters: input.filters,
509+
nativeQueries: queries,
510+
involving: input.involving,
511+
})
497512
)
498513
if (
499514
(!input.query.trim() &&
@@ -530,14 +545,18 @@ const liveKnowledgeSearch = defineAuthorizedKnowledgeUseCase({
530545
measureSearchStage('live.policies', () => loadLiveSearchPolicies(input)),
531546
measureSearchStage('live.accounts', () => listLiveAccounts(input, userId)),
532547
])
533-
const eligible = allAccounts
548+
const reachable = allAccounts
534549
.filter(
535550
(account) =>
536551
(!filters?.source || filters.source === account.provider) &&
537552
nativesFor(account).length > 0
538553
)
539554
.sort(compareAccounts)
540-
const nothingSearched = !queries && eligible.length === 0
555+
/** A person filter skips the sources that cannot apply it rather than return them unfiltered. */
556+
const eligible = reachable.filter(
557+
(account) => !input.involving || filtersByPerson(account.provider, input.involving)
558+
)
559+
const nothingSearched = !queries && reachable.length === 0
541560
const selected = eligible.slice(0, MAX_ACCOUNTS)
542561
const openingAccount = createConcurrencyLimit(ACCOUNT_OPEN_CONCURRENCY)
543562
annotateSearchDiagnostics({
@@ -615,6 +634,7 @@ const liveKnowledgeSearch = defineAuthorizedKnowledgeUseCase({
615634
policy: session.policy,
616635
query: input.query,
617636
native: queryNative,
637+
involving: input.involving,
618638
limit: input.topK,
619639
scopes: resolved.account.scopes,
620640
})
@@ -944,22 +964,29 @@ const liveKnowledgeSearch = defineAuthorizedKnowledgeUseCase({
944964
? [nothingSearchedGuidance(input, filters?.source, allAccounts.length > 0)]
945965
: []),
946966
liveSearchGuidance(
947-
accounts.filter((account) => account.status !== 'reconnect').map(({ provider }) => provider)
967+
accounts
968+
.filter((account) => account.status !== 'reconnect')
969+
.map(({ provider }) => provider),
970+
Boolean(input.involving)
948971
),
949972
].join('\n')
950-
for (const account of eligible.slice(MAX_ACCOUNTS)) {
951-
for (const { queryIndex } of nativesFor(account))
952-
accounts.push({
953-
accountId: account.id,
954-
provider: account.provider,
955-
displayName: account.displayName,
956-
...(queryIndex === undefined ? {} : { queryIndex }),
957-
status: 'unavailable',
958-
message: LIVE_OVER_ACCOUNT_LIMIT_MESSAGE,
959-
})
960-
}
973+
const unsearched: [LiveAccount[], string][] = [
974+
[eligible.slice(MAX_ACCOUNTS), LIVE_OVER_ACCOUNT_LIMIT_MESSAGE],
975+
[reachable.filter((account) => !eligible.includes(account)), LIVE_NO_PERSON_FILTER_MESSAGE],
976+
]
977+
for (const [skipped, message] of unsearched)
978+
for (const account of skipped)
979+
for (const { queryIndex } of nativesFor(account))
980+
accounts.push({
981+
accountId: account.id,
982+
provider: account.provider,
983+
displayName: account.displayName,
984+
...(queryIndex === undefined ? {} : { queryIndex }),
985+
status: 'unavailable',
986+
message,
987+
})
961988
for (const [queryIndex, query] of (queries ?? []).entries()) {
962-
if (!eligible.some((account) => targetsAccount(query, account)))
989+
if (!reachable.some((account) => targetsAccount(query, account)))
963990
accounts.push({
964991
accountId: query.accountId ?? '',
965992
provider: query.provider,

‎apps/sim/lib/sim-search/live/atlassian.test.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -338,3 +338,27 @@ describe('Confluence plain search ranking', () => {
338338
expect(own.nextCursor).toBe('page-2')
339339
})
340340
})
341+
342+
describe('Jira person filter', () => {
343+
const users = '/ex/jira/cloud/rest/api/3/user/search'
344+
const search = (api: NativeClient) =>
345+
searchAtlassian(api, 'jira', { query: '', limit: 20, scopes: [], involving: 'jan@acme.com' })
346+
347+
it('never takes a prefix match showing another address as the person', async () => {
348+
const api = client({ [users]: [{ accountId: 'other-id', emailAddress: 'jan@acme.com.au' }] })
349+
await expect(search(api)).rejects.toThrow('No single Jira user')
350+
expect(api.json).not.toHaveBeenCalledWith(
351+
'/ex/jira/cloud/rest/api/3/search/jql',
352+
expect.anything()
353+
)
354+
})
355+
it('scopes issues to the one user whose address Jira hides', async () => {
356+
const api = client({
357+
[users]: [{ accountId: 'jan-id' }],
358+
'/ex/jira/cloud/rest/api/3/search/jql': { issues: [] },
359+
})
360+
await search(api)
361+
const [, options] = api.json.mock.calls.find(([path]) => path.endsWith('/search/jql')) ?? []
362+
expect(options?.body?.jql).toBe('(assignee = "jan-id" OR reporter = "jan-id")')
363+
})
364+
})

0 commit comments

Comments
 (0)