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
10 changes: 9 additions & 1 deletion apps/sim/lib/api/contracts/knowledge/mcp.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { z } from 'zod'
import { workspaceSearchFiltersSchema } from '@/lib/api/contracts/knowledge/search'
import {
liveSearchInvolvingSchema,
workspaceSearchFiltersSchema,
} from '@/lib/api/contracts/knowledge/search'
import { mcpJsonRpcMessageSchema } from '@/lib/api/contracts/mcp'
import {
readDocumentInputSchema,
Expand Down Expand Up @@ -53,6 +56,11 @@ const mcpDateFilterFields = {
export const liveSearchMcpSchema = searchWorkspaceInputFieldsSchema
.extend({
...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.'
),
topK: searchWorkspaceInputFieldsSchema.shape.topK
.unwrap()
.optional()
Expand Down
13 changes: 13 additions & 0 deletions apps/sim/lib/api/contracts/knowledge/search.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { isValidEmailSyntax, normalizeEmail } from '@sim/utils/string'
import { z } from 'zod'
import {
nativeSearchQueriesSchema,
Expand Down Expand Up @@ -182,6 +183,18 @@ export { workspaceSearchFiltersSchema }

export type WorkspaceSearchFilters = z.output<typeof workspaceSearchFiltersSchema>

/**
* The person a live search is limited to: `me` or a normalized email. Checked by refinement
* rather than `z.email()` so a tools/list schema built from it carries no long email pattern.
*/
export const liveSearchInvolvingSchema = z
.string()
.transform(normalizeEmail)
.refine((value) => value === 'me' || isValidEmailSyntax(value), {
message:
'involving takes "me" or an email address, not a name. Find the person\'s email first, or search without involving.',
})

/** Chunks a search asks for at first paint, and once the reader asks for more; both within `topK`'s bound. */
export const WORKSPACE_KNOWLEDGE_SEARCH_LIMITS = { initial: 20, expanded: 50 } as const
export type WorkspaceKnowledgeSearchLimit =
Expand Down
5 changes: 4 additions & 1 deletion apps/sim/lib/knowledge/mcp/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import { toolError } from '@/lib/mcp/tool-result'
import {
LIVE_DATE_ORDER_MESSAGE,
LIVE_MORE_RANKED_BELOW_MESSAGE,
LIVE_NO_PERSON_FILTER_MESSAGE,
LIVE_NOT_STARTED_MESSAGE,
LIVE_OVER_ACCOUNT_LIMIT_MESSAGE,
readLiveDocument,
Expand Down Expand Up @@ -93,6 +94,7 @@ const LIVE_ACCOUNT_NOTES = {
dateOrderPartial: LIVE_DATE_ORDER_MESSAGE,
notSearchedByDeadline: LIVE_NOT_STARTED_MESSAGE,
notSearchedOverLimit: LIVE_OVER_ACCOUNT_LIMIT_MESSAGE,
notFilteredByPerson: LIVE_NO_PERSON_FILTER_MESSAGE,
}

/**
Expand Down Expand Up @@ -237,7 +239,7 @@ export function createKnowledgeMcpServer(context: KnowledgeMcpContext): McpServe
async (input: unknown, extra: { signal: AbortSignal }) =>
execute('search', knowledgeOperations.search, extra.signal, async (registry, signal) => {
const parsed = liveSearchMcpSchema.parse(input)
const { query, topK, nativeQueries, ...filters } = parsed
const { query, topK, nativeQueries, involving, ...filters } = parsed
const result = await searchLiveKnowledge.execute({
principal,
input: {
Expand All @@ -246,6 +248,7 @@ export function createKnowledgeMcpServer(context: KnowledgeMcpContext): McpServe
query,
topK: topK ?? liveSearchMcpDefaultTopK(parsed),
nativeQueries,
involving,
filters,
resultSecretRegistry: registry,
signal,
Expand Down
4 changes: 4 additions & 0 deletions apps/sim/lib/knowledge/search/diagnostics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@ export interface SearchDiagnosticMetadata {
documentFilterCount?: number
hasSourceFilter?: boolean
hasDateFilter?: boolean
/** Whether a live search was limited to the caller (`me`) or another person; never the email. */
involving?: 'me' | 'person'
tagFilterCount?: number
hasProvenance?: boolean
searchMode?: 'hybrid' | 'vector'
Expand Down Expand Up @@ -157,11 +159,13 @@ export function describeSearchRequest(input: {
query: string
filters?: WorkspaceSearchFilters
nativeQueries?: readonly NativeSearchQuery[]
involving?: string
}): SearchDiagnosticMetadata {
const { start, end } = nativeDateBounds({ filters: input.filters })
return {
queryTermCount: input.query.split(/\s+/).filter(Boolean).length,
sortBy: input.filters?.sortBy,
...(input.involving ? { involving: input.involving === 'me' ? 'me' : 'person' } : {}),
...(start && end
? { dateWindowDays: Math.round(((Date.parse(end) - Date.parse(start)) / DAY_MS) * 10) / 10 }
: {}),
Expand Down
42 changes: 42 additions & 0 deletions apps/sim/lib/sim-search/live/application.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ vi.mock('@/lib/sim-search/live/accounts', () => ({
}),
}))
vi.mock('@/lib/sim-search/live/providers', () => ({
filtersByPerson: (provider: string) => provider !== 'notion',
liveSearchGuidance: (providers: string[]) => `Live coverage: ${[...new Set(providers)]}`,
searchNativeProvider: mocks.search,
readNativeProvider: mocks.read,
Expand Down Expand Up @@ -1061,6 +1062,47 @@ describe('authorized live retrieval', () => {
})
expect(mocks.resolveAccount).not.toHaveBeenCalled()
})
describe('person filter', () => {
const notion = {
...account,
id: 'notion-account',
provider: 'notion' as const,
providerId: 'mcp:notion',
type: 'managed_mcp' as const,
displayName: 'Notion',
}
it('never searches a source that cannot filter by person, so no result is unfiltered', async () => {
mocks.accounts.mockResolvedValue([account, notion])
const result = await searchLiveKnowledge.execute({
principal,
input: { ...input, involving: 'jane@example.com' },
})
expect(mocks.resolveAccount).toHaveBeenCalledTimes(1)
expect(mocks.mcpCall).not.toHaveBeenCalled()
expect(result.live?.accounts).toContainEqual(
expect.objectContaining({
accountId: 'notion-account',
status: 'unavailable',
message: expect.stringContaining('cannot filter by this person'),
})
)
expect(result.live?.guidance).toBe('Live coverage: google_drive')
expect(result.retrieval.status).toBe('partial')
})
it('hands each provider search the normalized person', async () => {
await searchLiveKnowledge.execute({
principal,
input: { ...input, involving: ' Jane@Example.com ' },
})
expect(mocks.search.mock.calls[0]?.[2]).toMatchObject({ involving: 'jane@example.com' })
})
it('rejects a person that is neither me nor an email before any account is opened', async () => {
await expect(
searchLiveKnowledge.execute({ principal, input: { ...input, involving: 'Jane Doe' } })
).rejects.toThrow()
expect(mocks.resolveAccount).not.toHaveBeenCalled()
})
})
it('rechecks revoked account access on every document read', async () => {
const search = await searchLiveKnowledge.execute({ principal, input })
mocks.resolveAccount.mockRejectedValue(new NativeSearchError('reconnect', 'Revoked'))
Expand Down
63 changes: 45 additions & 18 deletions apps/sim/lib/sim-search/live/application.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { canonicalJson } from '@sim/utils/object'
import { compareStrings } from '@sim/utils/string'
import { z } from 'zod'
import type { WorkspaceSearchFilters } from '@/lib/api/contracts/knowledge'
import { liveSearchInvolvingSchema } from '@/lib/api/contracts/knowledge/search'
import type {
WorkspaceKnowledgeSearchData,
WorkspaceKnowledgeSearchResult,
Expand Down Expand Up @@ -82,7 +83,7 @@ import { isManagedSearchMcpProvider } from '@/lib/sim-search/live/managed-mcp-co
import { joinMessages } from '@/lib/sim-search/live/pages'
import { loadLiveSearchPolicies } from '@/lib/sim-search/live/policy-store'
import { LIVE_SEARCH_PROVIDER_IDS } from '@/lib/sim-search/live/provider-catalog'
import { liveSearchGuidance } from '@/lib/sim-search/live/providers'
import { filtersByPerson, liveSearchGuidance } from '@/lib/sim-search/live/providers'
import { LiveReadError } from '@/lib/sim-search/live/read-error'
import { encodedWindowEnd, READ_WINDOW_CHARACTERS } from '@/lib/sim-search/live/read-window'
import {
Expand Down Expand Up @@ -162,6 +163,8 @@ interface LiveSearchOptions {
topK: number
filters?: WorkspaceSearchFilters
nativeQueries?: NativeSearchQuery[]
/** Only items this person took part in: `me` or another person's lowercase email. */
involving?: string
signal?: AbortSignal
resultSecretRegistry?: ResolvedSecretTraceRegistry
}
Expand Down Expand Up @@ -295,6 +298,9 @@ export const LIVE_NOT_STARTED_MESSAGE =
'Not searched before the search deadline. Search this account alone or narrow the query.'
/** Account status for each eligible account beyond {@link MAX_ACCOUNTS}. */
export const LIVE_OVER_ACCOUNT_LIMIT_MESSAGE = `Not searched: one search covers at most ${MAX_ACCOUNTS} accounts. Search this source or account alone.`
/** Account status when a search filtered by person reaches a provider that cannot apply it. */
export const LIVE_NO_PERSON_FILTER_MESSAGE =
'Not searched: this source cannot filter by this person. Search it without involving.'
/** Previews center on the query's longest matching term, like indexed passages. */
const PREVIEW_CHARACTERS = 1800
/**
Expand Down Expand Up @@ -486,14 +492,23 @@ const liveKnowledgeSearch = defineAuthorizedKnowledgeUseCase({
const requestedFilters = input.filters
? workspaceSearchFiltersSchema.parse(input.filters)
: undefined
input = { ...input, filters: requestedFilters }
input = {
...input,
filters: requestedFilters,
involving: liveSearchInvolvingSchema.optional().parse(input.involving),
}
if (
(!input.query.trim() && !queries?.some((query) => query.query)) ||
queries?.some((query) => !query.query)
)
input = { ...input, filters: withImpliedListingBound(input.filters, new Date()) }
annotateSearchDiagnostics(
describeSearchRequest({ query: input.query, filters: input.filters, nativeQueries: queries })
describeSearchRequest({
query: input.query,
filters: input.filters,
nativeQueries: queries,
involving: input.involving,
})
)
if (
(!input.query.trim() &&
Expand Down Expand Up @@ -530,14 +545,18 @@ const liveKnowledgeSearch = defineAuthorizedKnowledgeUseCase({
measureSearchStage('live.policies', () => loadLiveSearchPolicies(input)),
measureSearchStage('live.accounts', () => listLiveAccounts(input, userId)),
])
const eligible = allAccounts
const reachable = allAccounts
.filter(
(account) =>
(!filters?.source || filters.source === account.provider) &&
nativesFor(account).length > 0
)
.sort(compareAccounts)
const nothingSearched = !queries && eligible.length === 0
/** A person filter skips the sources that cannot apply it rather than return them unfiltered. */
const eligible = reachable.filter(
(account) => !input.involving || filtersByPerson(account.provider, input.involving)
)
const nothingSearched = !queries && reachable.length === 0
const selected = eligible.slice(0, MAX_ACCOUNTS)
const openingAccount = createConcurrencyLimit(ACCOUNT_OPEN_CONCURRENCY)
annotateSearchDiagnostics({
Expand Down Expand Up @@ -615,6 +634,7 @@ const liveKnowledgeSearch = defineAuthorizedKnowledgeUseCase({
policy: session.policy,
query: input.query,
native: queryNative,
involving: input.involving,
limit: input.topK,
scopes: resolved.account.scopes,
})
Expand Down Expand Up @@ -944,22 +964,29 @@ const liveKnowledgeSearch = defineAuthorizedKnowledgeUseCase({
? [nothingSearchedGuidance(input, filters?.source, allAccounts.length > 0)]
: []),
liveSearchGuidance(
accounts.filter((account) => account.status !== 'reconnect').map(({ provider }) => provider)
accounts
.filter((account) => account.status !== 'reconnect')
.map(({ provider }) => provider),
Boolean(input.involving)
),
].join('\n')
for (const account of eligible.slice(MAX_ACCOUNTS)) {
for (const { queryIndex } of nativesFor(account))
accounts.push({
accountId: account.id,
provider: account.provider,
displayName: account.displayName,
...(queryIndex === undefined ? {} : { queryIndex }),
status: 'unavailable',
message: LIVE_OVER_ACCOUNT_LIMIT_MESSAGE,
})
}
const unsearched: [LiveAccount[], string][] = [
[eligible.slice(MAX_ACCOUNTS), LIVE_OVER_ACCOUNT_LIMIT_MESSAGE],
[reachable.filter((account) => !eligible.includes(account)), LIVE_NO_PERSON_FILTER_MESSAGE],
]
for (const [skipped, message] of unsearched)
for (const account of skipped)
for (const { queryIndex } of nativesFor(account))
accounts.push({
accountId: account.id,
provider: account.provider,
displayName: account.displayName,
...(queryIndex === undefined ? {} : { queryIndex }),
status: 'unavailable',
message,
})
for (const [queryIndex, query] of (queries ?? []).entries()) {
if (!eligible.some((account) => targetsAccount(query, account)))
if (!reachable.some((account) => targetsAccount(query, account)))
accounts.push({
accountId: query.accountId ?? '',
provider: query.provider,
Expand Down
24 changes: 24 additions & 0 deletions apps/sim/lib/sim-search/live/atlassian.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -338,3 +338,27 @@ describe('Confluence plain search ranking', () => {
expect(own.nextCursor).toBe('page-2')
})
})

describe('Jira person filter', () => {
const users = '/ex/jira/cloud/rest/api/3/user/search'
const search = (api: NativeClient) =>
searchAtlassian(api, 'jira', { query: '', limit: 20, scopes: [], involving: 'jan@acme.com' })

it('never takes a prefix match showing another address as the person', async () => {
const api = client({ [users]: [{ accountId: 'other-id', emailAddress: 'jan@acme.com.au' }] })
await expect(search(api)).rejects.toThrow('No single Jira user')
expect(api.json).not.toHaveBeenCalledWith(
'/ex/jira/cloud/rest/api/3/search/jql',
expect.anything()
)
})
it('scopes issues to the one user whose address Jira hides', async () => {
const api = client({
[users]: [{ accountId: 'jan-id' }],
'/ex/jira/cloud/rest/api/3/search/jql': { issues: [] },
})
await search(api)
const [, options] = api.json.mock.calls.find(([path]) => path.endsWith('/search/jql')) ?? []
expect(options?.body?.jql).toBe('(assignee = "jan-id" OR reporter = "jan-id")')
})
})
Loading
Loading