Skip to content

Commit 69cbb15

Browse files
committed
fix(search-mcp): match calendar person by account email, resolve Jira people across sites, skip Confluence for colleague emails
1 parent b4fc7ac commit 69cbb15

6 files changed

Lines changed: 77 additions & 33 deletions

File tree

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1083,7 +1083,7 @@ describe('authorized live retrieval', () => {
10831083
expect.objectContaining({
10841084
accountId: 'notion-account',
10851085
status: 'unavailable',
1086-
message: expect.stringContaining('cannot filter by person'),
1086+
message: expect.stringContaining('cannot filter by this person'),
10871087
})
10881088
)
10891089
expect(result.live?.guidance).toBe('Live coverage: google_drive')

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -300,7 +300,7 @@ export const LIVE_NOT_STARTED_MESSAGE =
300300
export const LIVE_OVER_ACCOUNT_LIMIT_MESSAGE = `Not searched: one search covers at most ${MAX_ACCOUNTS} accounts. Search this source or account alone.`
301301
/** Account status when a search filtered by person reaches a provider that cannot apply it. */
302302
export const LIVE_NO_PERSON_FILTER_MESSAGE =
303-
'Not searched: this source cannot filter by person. Search it without involving.'
303+
'Not searched: this source cannot filter by this person. Search it without involving.'
304304
/** Previews center on the query's longest matching term, like indexed passages. */
305305
const PREVIEW_CHARACTERS = 1800
306306
/**
@@ -554,7 +554,7 @@ const liveKnowledgeSearch = defineAuthorizedKnowledgeUseCase({
554554
.sort(compareAccounts)
555555
/** A person filter skips the sources that cannot apply it rather than return them unfiltered. */
556556
const eligible = reachable.filter(
557-
(account) => !input.involving || filtersByPerson(account.provider)
557+
(account) => !input.involving || filtersByPerson(account.provider, input.involving)
558558
)
559559
const nothingSearched = !queries && reachable.length === 0
560560
const selected = eligible.slice(0, MAX_ACCOUNTS)

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

Lines changed: 33 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,28 @@ interface SitePage {
142142
ranking?: 'relevance' | 'unavailable'
143143
}
144144

145+
/**
146+
* The account ID of the one user a site finds for an email, or undefined. Jira hides most email
147+
* addresses, so a lone match for an email query is that person. Account IDs span sites, so a
148+
* person found on any searched site applies to all of them.
149+
*/
150+
async function jiraAccountId(
151+
client: NativeClient,
152+
cloudId: string,
153+
email: string
154+
): Promise<string | undefined> {
155+
const found = array(
156+
await client.json(`/ex/jira/${segment(cloudId)}/rest/api/3/user/search`, {
157+
query: { query: email, maxResults: '2' },
158+
memo: true,
159+
})
160+
)
161+
const exact = found.filter((row) => string(row.emailAddress).toLowerCase() === email)
162+
const users = exact.length ? exact : found
163+
const accountId = string(users[0]?.accountId)
164+
return users.length === 1 && /^[\w:-]+$/.test(accountId) ? accountId : undefined
165+
}
166+
145167
/**
146168
* The JQL or CQL clause limiting a search to a person: issues they are assigned or reported, or
147169
* pages they created or edited. Jira finds anyone else by email (Atlassian account IDs span
@@ -164,17 +186,18 @@ async function atlassianPersonClause(
164186
}
165187
let user = 'currentUser()'
166188
if (involving !== 'me') {
167-
const found = array(
168-
await client.json(`/ex/jira/${segment(string(sites[0]?.id))}/rest/api/3/user/search`, {
169-
query: { query: involving, maxResults: '2' },
170-
memo: true,
171-
})
189+
const lookups = await Promise.allSettled(
190+
sites.map((site) => jiraAccountId(client, string(site.id), involving))
191+
)
192+
const failed = lookups.find((lookup) => lookup.status === 'rejected')
193+
if (failed && lookups.every((lookup) => lookup.status === 'rejected')) throw failed.reason
194+
const accountIds = new Set(
195+
lookups.flatMap((lookup) =>
196+
lookup.status === 'fulfilled' && lookup.value ? [lookup.value] : []
197+
)
172198
)
173-
// Jira hides most email addresses, so a lone match for an email query is that person.
174-
const exact = found.filter((row) => string(row.emailAddress).toLowerCase() === involving)
175-
const users = exact.length ? exact : found
176-
const accountId = string(users[0]?.accountId)
177-
if (users.length !== 1 || !/^[\w:-]+$/.test(accountId))
199+
const [accountId] = accountIds
200+
if (accountIds.size !== 1 || !accountId)
178201
throw new NativeSearchError('unavailable', 'No single Jira user has this email.')
179202
user = JSON.stringify(accountId)
180203
}

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

Lines changed: 22 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -568,13 +568,12 @@ function calendarOccurrenceKey(row: Record<string, unknown>): string {
568568
}
569569

570570
/**
571-
* Whether a person organizes or attends an event without having declined it: `me` is the
572-
* calendar owner, anyone else is matched by email. Always true without a person.
571+
* Whether the person with this email organizes or attends an event without having declined it.
572+
* Always true without a person.
573573
*/
574-
function attendedBy(event: Record<string, unknown>, involving: string | undefined): boolean {
575-
if (!involving) return true
576-
const isPerson = (party: Record<string, unknown>) =>
577-
involving === 'me' ? party.self === true : string(party.email).toLowerCase() === involving
574+
function attendedBy(event: Record<string, unknown>, email: string | undefined): boolean {
575+
if (!email) return true
576+
const isPerson = (party: Record<string, unknown>) => string(party.email).toLowerCase() === email
578577
return (
579578
isPerson(object(event.organizer)) ||
580579
array(event.attendees).some(
@@ -613,8 +612,22 @@ export async function searchCalendar(
613612
.slice(0, 20)
614613
.sort((left, right) => Number(right.primary === true) - Number(left.primary === true))
615614
const chronological = hasDateBounds(input.filters) || Boolean(dateSortDirection(input.filters))
616-
/** Without text, another person's email narrows the search to events they are invited to. */
617-
const q = nativeText(input) || (input.involving === 'me' ? undefined : input.involving)
615+
/**
616+
* The person's email: `me` is the connected account, whose primary calendar ID is its address,
617+
* since a shared calendar's `self` flag marks that calendar's owner rather than the caller.
618+
*/
619+
const person =
620+
input.involving === 'me'
621+
? string(
622+
object(await client.json('/calendar/v3/calendars/primary', { memo: true })).id
623+
).toLowerCase()
624+
: input.involving
625+
if (input.involving && !person?.includes('@'))
626+
throw new NativeSearchError('unavailable', 'Calendar did not return your account address.')
627+
/** Another person's email narrows the provider search to events they are invited to. */
628+
const q = [nativeText(input), input.involving === 'me' ? '' : input.involving]
629+
.filter(Boolean)
630+
.join(' ')
618631
const pages = await mapWithConcurrency(rows, 4, async (row) => {
619632
const calendarId = string(row.id)
620633
try {
@@ -660,7 +673,7 @@ export async function searchCalendar(
660673
)
661674
const perCalendar = searched.map(({ data, calendarId, timeZone }) =>
662675
array(data.items)
663-
.filter((event) => event.status !== 'cancelled' && attendedBy(event, input.involving))
676+
.filter((event) => event.status !== 'cancelled' && attendedBy(event, person))
664677
.map((event) => ({
665678
...eventDocument(event, calendarId, input.policy?.includeAttendees, timeZone),
666679
dedupeKey: calendarOccurrenceKey(event),

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

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -124,16 +124,20 @@ describe('native search endpoints', () => {
124124
start: { dateTime: '2026-09-24T09:00:00Z' },
125125
...extra,
126126
})
127-
api.json
128-
.mockResolvedValueOnce({ items: [{ id: 'primary', primary: true }] })
129-
.mockResolvedValueOnce({
127+
const me = 'member@example.com'
128+
api.json.mockImplementation(async (path) => {
129+
if (path.endsWith('/calendarList')) return { items: [{ id: me, primary: true }] }
130+
if (path.endsWith('/calendars/primary')) return { id: me }
131+
return {
130132
items: [
131-
event('organized', { organizer: { self: true } }),
132-
event('attended', { attendees: [{ self: true, responseStatus: 'accepted' }] }),
133-
event('declined', { attendees: [{ self: true, responseStatus: 'declined' }] }),
134-
event('others', { attendees: [{ email: 'jane@example.com' }] }),
133+
event('organized', { organizer: { email: me } }),
134+
event('attended', { attendees: [{ email: me, responseStatus: 'accepted' }] }),
135+
event('declined', { attendees: [{ email: me, responseStatus: 'declined' }] }),
136+
// A shared calendar's own copy marks its owner, not the caller, as self.
137+
event('shared', { organizer: { self: true, email: 'jane@example.com' } }),
135138
],
136-
})
139+
}
140+
})
137141
const result = await searchCalendar(api, { ...input, query: '', involving: 'me' })
138142
expect(result.documents.map(({ id }) => id)).toEqual(['organized', 'attended'])
139143
})

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

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,8 @@ interface NativeProvider {
5050
guide: NativeQueryGuide
5151
/** What the involving filter keeps for this provider; providers without it skip such searches. */
5252
involving?: string
53+
/** The involving filter accepts only `me`: the provider cannot find anyone else by email. */
54+
involvingMeOnly?: true
5355
/** Plain queries must contain every word, so an underfilled search retries with any term. */
5456
requiresEveryTerm?: true
5557
/**
@@ -210,6 +212,7 @@ export const LIVE_SEARCH_PROVIDERS = {
210212
},
211213
confluence: {
212214
involving: 'pages you created or edited; involving: me only',
215+
involvingMeOnly: true,
213216
guide: {
214217
syntax:
215218
'CQL: siteSearch ~ "a few words" is Confluence relevance search and ranks pages about the topic first, so use it for topic, acronym and how-to lookups. text ~ "term" and title ~ "term" (title ~ "win*" for a prefix) match pages containing those words or their variants without that ranking, so keep them for a specific identifier or term; text ~ "\\"exact phrase\\"" matches a phrase. Combine with type IN (page, blogpost) and space = KEY (quote keys starting with a digit) using AND/OR/NOT and parentheses; add ORDER BY lastmodified DESC only when recency matters more than relevance.',
@@ -372,9 +375,10 @@ export function searchNativeProvider(
372375
return adapter.search(client, input, origin)
373376
}
374377

375-
/** True when the provider can limit a search to the items one person took part in. */
376-
export function filtersByPerson(provider: LiveSearchProviderId): boolean {
377-
return 'involving' in LIVE_SEARCH_PROVIDERS[provider]
378+
/** True when the provider can limit a search to the items this person (`me` or an email) took part in. */
379+
export function filtersByPerson(provider: LiveSearchProviderId, involving: string): boolean {
380+
const adapter: NativeProvider | ManagedMcpProvider = LIVE_SEARCH_PROVIDERS[provider]
381+
return 'involving' in adapter && (involving === 'me' || !('involvingMeOnly' in adapter))
378382
}
379383

380384
/** True when the provider's plain-text search matches only items containing every query word. */

0 commit comments

Comments
 (0)