Skip to content

Commit 2ffbae6

Browse files
authored
fix(search): keep activity paging and labels truthful under busy sources and failures (#10561)
* fix(search): keep activity paging and labels truthful under busy sources and failures - Jira reads its created listing with relative-minute bounds and assigned issues by the moment of assignment (assignee CHANGED TO currentUser() DURING, from each issue's history) - Confluence places pages at the member's own latest edit from version history, dropping pages they did not edit in the window, and reads listings whose order is not the member's action whole; CQL bounds widen by the widest time zone offsets instead of a day - A listing that cannot reach its bound stops only its own account, with an accurate status - A failed account is retried once, then reported - Search MCP charges one rate-limit operation per account read - Continuations may change topK; Assistant items drop the duplicate citationUrl and items drop accountId - Calendar reports an overfull week only when a slice exhausts the whole budget - Removes the never-emitted mentioned action and approximateTime * refactor(search): read Confluence version histories together and tidy activity constants * fix(search): stop only the activity source that cannot advance and pick each item once per window - A page with no progress stops the accounts pinning the horizon; the others page on - A failed account the listing ends before retrying is reported - Confluence pages and Jira assignments are placed at their latest moment in the whole window, so a later page never repeats them; an unread version history reports partial coverage - Confluence comments before the window are left out - Search MCP charges a continuation by the accounts its cursor still names * fix(search): charge Search MCP activity by the accounts a page read, after admission * fix(search): admit every activity account read before reading, through the MCP rate limit * chore(search): regenerate Mothership tool contracts after rebasing * fix(search): read Jira assignments at a fixed page size and check cancellation around admission * chore(search): regenerate Mothership tool contracts after rebasing * fix(search): declare optional activity window fields as possibly undefined for the synced worker contract
1 parent 03b8fc6 commit 2ffbae6

17 files changed

Lines changed: 1101 additions & 367 deletions

‎apps/sim/lib/api/contracts/mothership-assistant-tools.ts‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -375,14 +375,18 @@ export const listMyActivityInputFieldsSchema = z
375375
.max(40_000)
376376
.optional()
377377
.describe(
378-
'nextCursor from the previous page, with the same startDate, endDate, source and topK. Pages continue newest first without gaps.'
378+
'nextCursor from the previous page, with the same startDate, endDate and source; topK may change. Pages continue newest first without gaps.'
379379
),
380380
})
381381
.strict()
382382

383383
/** Rules shared by every activity input schema built from {@link listMyActivityInputFieldsSchema}. */
384384
export function refineActivityWindow(
385-
input: { startDate?: string; endDate?: string; cursor?: string },
385+
input: {
386+
startDate?: string | undefined
387+
endDate?: string | undefined
388+
cursor?: string | undefined
389+
},
386390
context: z.RefinementCtx
387391
) {
388392
/** A continuation reads the window its signed cursor fixed, however long ago that was. */
@@ -434,7 +438,6 @@ const activityActionSchema = z.enum([
434438
'replied',
435439
'attended',
436440
'assigned',
437-
'mentioned',
438441
])
439442
export type ActivityAction = z.output<typeof activityActionSchema>
440443

@@ -443,15 +446,12 @@ const activityItemSchema = z.object({
443446
documentId: z.string(),
444447
timestamp: z.string(),
445448
source: liveSearchProviderSchema,
446-
accountId: z.string(),
447449
action: activityActionSchema,
448450
title: z.string(),
449451
url: z.string().nullable(),
450452
container: z.string().optional(),
451453
collaborators: z.array(z.string()),
452454
snippet: z.string(),
453-
/** The timestamp is the item's last update, possibly by someone else, not the person's action. */
454-
approximateTime: z.literal(true).optional(),
455455
})
456456

457457
const listMyActivityResultSchema = z.object({
@@ -655,7 +655,7 @@ export const assistantToolContracts = [
655655
id: 'list_my_activity',
656656
route: 'sim',
657657
description:
658-
'List what you did across your connected sources in a date window, newest first: messages and mail you sent or replied to, meetings you attended, Jira issues you created or are assigned, Confluence pages you created or edited and comments you wrote. Each item has a documentId for read_document. Follow nextCursor for more. sources reports each source: not_connected and reconnect carry the provider to connect with oauth_get_auth_link.',
658+
'List what you did across your connected sources in a date window, newest first: Slack messages and Gmail mail you sent (replied when the message answers another), Google Calendar meetings you organized or accepted, Jira issues you created or that were assigned to you, Confluence pages you created or edited and comments you wrote. Each item has a documentId for read_document. Follow nextCursor for more; a source that failed and recovers on a later page can return entries older than that page. sources reports each source: not_connected and reconnect carry the provider to connect with oauth_get_auth_link.',
659659
inputSchema: listMyActivityInputSchema,
660660
},
661661
{

‎apps/sim/lib/knowledge/mcp/my-activity.ts‎

Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
22
import type { Principal } from '@sim/auth/principal'
33
import type { NextRequest } from 'next/server'
44
import { listMyActivityMcpSchema } from '@/lib/api/contracts/knowledge/mcp'
5+
import { OrchestrationError } from '@/lib/core/orchestration/types'
56
import { knowledgeOperations } from '@/lib/knowledge/application/operations'
67
import {
78
KNOWLEDGE_MCP_READ_ONLY,
@@ -17,12 +18,6 @@ interface ListMyActivityToolContext {
1718
request: NextRequest
1819
}
1920

20-
/**
21-
* Provider reads one call makes, for the rate limit: about one listing per connected source,
22-
* which is more than a single search's share.
23-
*/
24-
const LIST_MY_ACTIVITY_COST = 2
25-
2621
/**
2722
* Registers `list_my_activity`: what the caller did across their connected sources in a window,
2823
* newest first, with a status per source that names the ones to connect.
@@ -36,7 +31,7 @@ export function registerListMyActivityTool(
3631
{
3732
title: 'List my activity',
3833
description:
39-
'List what you did across your connected sources in a date window, newest first: Slack messages and Gmail mail you sent or replied to, Google Calendar meetings you attended, Jira issues you created or are assigned, and Confluence pages you created or edited and comments you wrote. Use it for standups, weekly reports and open action items. Defaults to the last 7 days; the window spans at most 92 days. Each item has a documentId for read_document and its url to cite. approximateTime marks a time that is the item’s last update rather than your own action. When truncated is true, call again with nextCursor and the same arguments: pages continue without gaps. sources reports every source: not_connected and reconnect carry connect.url, where you connect that account.',
34+
'List what you did across your connected sources in a date window, newest first, each at the time of your own action: Slack messages and Gmail mail you sent (replied when the message answers another), Google Calendar meetings you organized or accepted (attended), Jira issues you created or that were assigned to you, and Confluence pages you created or edited and comments you wrote. Use it for standups, weekly reports and open action items. Defaults to the last 7 days; the window spans at most 92 days. Each item has a documentId for read_document and its url to cite. When truncated is true, call again with nextCursor and the same startDate, endDate and source (topK may change): pages continue without gaps, though a source that failed and recovers on a later page can return entries older than that page. sources reports every source: not_connected and reconnect carry connect.url, where you connect that account.',
4035
inputSchema: listMyActivityMcpSchema,
4136
annotations: KNOWLEDGE_MCP_READ_ONLY,
4237
},
@@ -45,16 +40,28 @@ export function registerListMyActivityTool(
4540
'list_my_activity',
4641
knowledgeOperations.listActivity,
4742
extra.signal,
48-
async (registry, signal) => {
43+
async (registry, signal, charge) => {
4944
const parsed = listMyActivityMcpSchema.parse(input)
5045
const result = await listMyActivity.execute({
5146
principal,
52-
input: { ...parsed, organizationId, resultSecretRegistry: registry, signal },
47+
input: {
48+
...parsed,
49+
organizationId,
50+
resultSecretRegistry: registry,
51+
signal,
52+
/**
53+
* Each account is a separate provider listing: beyond the one operation the call
54+
* was admitted with, one more per further account, admitted before any is read.
55+
*/
56+
admitReads: async (accounts) => {
57+
const rejected = await charge(accounts - 1)
58+
if (rejected) throw new OrchestrationError('unavailable', rejected)
59+
},
60+
},
5361
request,
5462
})
5563
return projectResult(result, registry)
56-
},
57-
LIST_MY_ACTIVITY_COST
64+
}
5865
)
5966
)
6067
}

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

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,14 @@ interface KnowledgeMcpContext {
5454
listMyActivity?: boolean
5555
}
5656

57+
/** What a caller is told when the rate limit refuses a call, with when to retry if known. */
58+
function rateLimitMessage(limited: Response): string {
59+
const retryAfter = parseRetryAfter(limited.headers.get('Retry-After'), Number.MAX_SAFE_INTEGER)
60+
return retryAfter === null
61+
? 'API rate limit exceeded. Please try again later.'
62+
: `API rate limit exceeded. Retry in ${Math.ceil(retryAfter / 1000)} seconds.`
63+
}
64+
5765
/** A request owns its server; no credential or principal survives into another HTTP request. */
5866
export function createKnowledgeMcpServer(context: KnowledgeMcpContext): McpServer {
5967
const { request, auth, organizationId } = context
@@ -71,17 +79,17 @@ export function createKnowledgeMcpServer(context: KnowledgeMcpContext): McpServe
7179
signal.throwIfAborted()
7280
if (limited) {
7381
outcome = 'rate_limited'
74-
const retryAfter = parseRetryAfter(
75-
limited.headers.get('Retry-After'),
76-
Number.MAX_SAFE_INTEGER
77-
)
78-
return toolError(
79-
retryAfter === null
80-
? 'API rate limit exceeded. Please try again later.'
81-
: `API rate limit exceeded. Retry in ${Math.ceil(retryAfter / 1000)} seconds.`
82-
)
82+
return toolError(rateLimitMessage(limited))
8383
}
84-
const result = await run(new ResolvedSecretTraceRegistry(), signal)
84+
const result = await run(new ResolvedSecretTraceRegistry(), signal, async (more) => {
85+
if (more <= 0) return undefined
86+
signal.throwIfAborted()
87+
const rejected = await v2RateLimits.publicApi.enforce(request, auth, operation, more)
88+
signal.throwIfAborted()
89+
if (!rejected) return undefined
90+
outcome = 'rate_limited'
91+
return rateLimitMessage(rejected)
92+
})
8593
outcome = signal.aborted ? 'cancelled' : result.isError ? 'error' : 'success'
8694
resultChars = resultCharacters(result)
8795
return result

‎apps/sim/lib/knowledge/mcp/tool-runner.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,15 @@ export type KnowledgeMcpToolRunner = (
2222
toolName: SearchMcpActivityInput['toolName'],
2323
operation: ApplicationOperation,
2424
toolSignal: AbortSignal,
25-
run: (registry: ResolvedSecretTraceRegistry, signal: AbortSignal) => Promise<CallToolResult>,
25+
run: (
26+
registry: ResolvedSecretTraceRegistry,
27+
signal: AbortSignal,
28+
/**
29+
* Admits further operations for a call whose size is known only once it runs, before it does
30+
* that work. Resolves to the rate-limit message when the budget cannot cover them.
31+
*/
32+
charge: (cost: number) => Promise<string | undefined>
33+
) => Promise<CallToolResult>,
2634
/** Operations the call performs for the rate limit, such as each document a batched read reads. */
2735
cost?: number
2836
) => Promise<CallToolResult>

‎apps/sim/lib/mothership/chat/citation-evidence.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ export function toCitationResult(
4545
if (toolName === 'list_my_activity' && typeof result.documentName !== 'string')
4646
return {
4747
citationId: result.citationId,
48-
citationUrl: result.citationUrl,
48+
citationUrl: result.url,
4949
documentName: result.title,
5050
connectorType: result.source,
5151
sourceDate: result.timestamp,

‎apps/sim/lib/mothership/generated/sim-assistant-tools.generated.ts‎

Lines changed: 49 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -398,14 +398,18 @@ export const listMyActivityInputFieldsSchema = z
398398
.max(40_000)
399399
.optional()
400400
.describe(
401-
'nextCursor from the previous page, with the same startDate, endDate, source and topK. Pages continue newest first without gaps.'
401+
'nextCursor from the previous page, with the same startDate, endDate and source; topK may change. Pages continue newest first without gaps.'
402402
),
403403
})
404404
.strict()
405405

406406
/** Rules shared by every activity input schema built from {@link listMyActivityInputFieldsSchema}. */
407407
export function refineActivityWindow(
408-
input: { startDate?: string; endDate?: string; cursor?: string },
408+
input: {
409+
startDate?: string | undefined
410+
endDate?: string | undefined
411+
cursor?: string | undefined
412+
},
409413
context: z.RefinementCtx
410414
) {
411415
/** A continuation reads the window its signed cursor fixed, however long ago that was. */
@@ -457,7 +461,6 @@ const activityActionSchema = z.enum([
457461
'replied',
458462
'attended',
459463
'assigned',
460-
'mentioned',
461464
])
462465
export type ActivityAction = z.output<typeof activityActionSchema>
463466

@@ -466,15 +469,12 @@ const activityItemSchema = z.object({
466469
documentId: z.string(),
467470
timestamp: z.string(),
468471
source: liveSearchProviderSchema,
469-
accountId: z.string(),
470472
action: activityActionSchema,
471473
title: z.string(),
472474
url: z.string().nullable(),
473475
container: z.string().optional(),
474476
collaborators: z.array(z.string()),
475477
snippet: z.string(),
476-
/** The timestamp is the item's last update, possibly by someone else, not the person's action. */
477-
approximateTime: z.literal(true).optional(),
478478
})
479479

480480
const listMyActivityResultSchema = z.object({
@@ -493,6 +493,10 @@ export type ListMyActivityResult = z.output<typeof listMyActivityResultSchema>
493493
* Organization directory lookups. The bounds mirror the People page's search limits
494494
* (`lib/people/validation`) as literals, so the worker's generated copy stays standalone.
495495
*/
496+
function peopleFieldFilter(description: string) {
497+
return z.string().trim().min(1).max(200).optional().describe(description)
498+
}
499+
496500
export const searchPeopleInputSchema = z
497501
.object({
498502
query: z
@@ -512,38 +516,64 @@ export const searchPeopleInputSchema = z
512516
.describe(
513517
'A personId from an earlier result, to show that person with their managers and direct reports. Used instead of query.'
514518
),
519+
name: peopleFieldFilter('Only people whose name contains this text.'),
520+
email: z
521+
.string()
522+
.trim()
523+
.min(3)
524+
.max(320)
525+
.optional()
526+
.describe('Only the person with this exact email address.'),
527+
title: peopleFieldFilter('Only people whose title contains this text.'),
528+
department: peopleFieldFilter('Only people whose department contains this text.'),
529+
location: peopleFieldFilter('Only people whose location contains this text.'),
530+
managerPersonId: z
531+
.string()
532+
.min(1)
533+
.max(255)
534+
.optional()
535+
.describe('Only the direct reports of this personId.'),
515536
cursor: z
516537
.string()
517538
.min(1)
518539
.max(1024)
519540
.optional()
520-
.describe('nextCursor from the previous page of the same query.'),
541+
.describe('nextCursor from the previous page of the same query and filters.'),
521542
})
522543
.strict()
523-
.refine((input) => !input.personId || (input.query === undefined && !input.cursor), {
524-
path: ['personId'],
525-
message: 'Pass either personId or a query with its cursor, not both.',
526-
})
544+
.refine(
545+
({ personId, ...listing }) =>
546+
!personId || Object.values(listing).every((value) => value === undefined),
547+
{
548+
path: ['personId'],
549+
message: 'Pass either personId or a query with its filters and cursor, not both.',
550+
}
551+
)
527552

528553
/**
529-
* The caller's own questions to Sim over a window, oldest first. The 92-day window and the page
530-
* bounds are literals so the worker's generated copy stays standalone.
554+
* The caller's own questions to Sim over a window, newest first by default. The 92-day window
555+
* and the page bounds are literals so the worker's generated copy stays standalone.
531556
*/
532557
export const listMyChatHistoryInputSchema = z
533558
.object({
534559
startDate: z
535560
.string()
536561
.datetime({ offset: true })
562+
.optional()
537563
.describe(
538-
'Inclusive lower bound on when you asked, as an ISO datetime with your timezone offset. For whole days, use local midnight on the first day.'
564+
'Inclusive start of the window, an ISO datetime with your timezone offset. Defaults to 7 days before endDate; the window spans at most 92 days.'
539565
),
540566
endDate: z
541567
.string()
542568
.datetime({ offset: true })
543569
.optional()
544570
.describe(
545-
'Exclusive upper bound, at most 92 days after startDate; defaults to now. For whole days, use local midnight after the final day.'
571+
'Exclusive end of the window, an ISO datetime with your timezone offset. Defaults to now; a later time reads up to now. For whole days, use local midnight after the final day.'
546572
),
573+
sortBy: z
574+
.enum(['newest', 'oldest'])
575+
.optional()
576+
.describe('newest (the default) or oldest first.'),
547577
topK: z
548578
.number()
549579
.int()
@@ -556,7 +586,7 @@ export const listMyChatHistoryInputSchema = z
556586
.min(1)
557587
.max(1024)
558588
.optional()
559-
.describe('nextCursor from the previous page of the same window.'),
589+
.describe('nextCursor from the previous page of the same window and order.'),
560590
includeAnswers: z
561591
.boolean()
562592
.optional()
@@ -634,21 +664,21 @@ export const assistantToolContracts = [
634664
id: 'search_people',
635665
route: 'sim',
636666
description:
637-
'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.',
667+
'Look up people in this organization’s directory by name, email, title, department, or location, with query across all of them or a filter per field; managerPersonId lists someone’s direct reports. Returns each person’s title, department, location, email, start date, time zone, Slack user ID, manager, and direct report count. 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.',
638668
inputSchema: searchPeopleInputSchema,
639669
},
640670
{
641671
id: 'list_my_chat_history',
642672
route: 'sim',
643673
description:
644-
'List the questions you asked Sim (the Assistant, agent chats, the Slack app and Search MCP chat) in a time window, oldest first, each with a link to its conversation. Covers only your own conversations that still exist.',
674+
'List the questions you asked Sim (the Assistant, agent chats, the Slack app and Search MCP chat) in a time window, newest first, each with a link to its conversation. Covers only your own conversations that still exist.',
645675
inputSchema: listMyChatHistoryInputSchema,
646676
},
647677
{
648678
id: 'list_my_activity',
649679
route: 'sim',
650680
description:
651-
'List what you did across your connected sources in a date window, newest first: messages and mail you sent or replied to, meetings you attended, Jira issues you created or are assigned, Confluence pages you created or edited and comments you wrote. Each item has a documentId for read_document. Follow nextCursor for more. sources reports each source: not_connected and reconnect carry the provider to connect with oauth_get_auth_link.',
681+
'List what you did across your connected sources in a date window, newest first: Slack messages and Gmail mail you sent (replied when the message answers another), Google Calendar meetings you organized or accepted, Jira issues you created or that were assigned to you, Confluence pages you created or edited and comments you wrote. Each item has a documentId for read_document. Follow nextCursor for more; a source that failed and recovers on a later page can return entries older than that page. sources reports each source: not_connected and reconnect carry the provider to connect with oauth_get_auth_link.',
652682
inputSchema: listMyActivityInputSchema,
653683
},
654684
{

0 commit comments

Comments
 (0)