Skip to content
Open
8 changes: 2 additions & 6 deletions apps/sim/lib/api/contracts/mothership-assistant-tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -375,7 +375,7 @@ export const listMyActivityInputFieldsSchema = z
.max(40_000)
.optional()
.describe(
'nextCursor from the previous page, with the same startDate, endDate, source and topK. Pages continue newest first without gaps.'
'nextCursor from the previous page, with the same startDate, endDate and source; topK may change. Pages continue newest first without gaps.'
),
})
.strict()
Expand Down Expand Up @@ -434,7 +434,6 @@ const activityActionSchema = z.enum([
'replied',
'attended',
'assigned',
'mentioned',
])
export type ActivityAction = z.output<typeof activityActionSchema>

Expand All @@ -443,15 +442,12 @@ const activityItemSchema = z.object({
documentId: z.string(),
timestamp: z.string(),
source: liveSearchProviderSchema,
accountId: z.string(),
action: activityActionSchema,
title: z.string(),
url: z.string().nullable(),
container: z.string().optional(),
collaborators: z.array(z.string()),
snippet: z.string(),
/** The timestamp is the item's last update, possibly by someone else, not the person's action. */
approximateTime: z.literal(true).optional(),
})

const listMyActivityResultSchema = z.object({
Expand Down Expand Up @@ -650,7 +646,7 @@ export const assistantToolContracts = [
id: 'list_my_activity',
route: 'sim',
description:
'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.',
'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.',
inputSchema: listMyActivityInputSchema,
},
{
Expand Down
29 changes: 18 additions & 11 deletions apps/sim/lib/knowledge/mcp/my-activity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import type { Principal } from '@sim/auth/principal'
import type { NextRequest } from 'next/server'
import { listMyActivityMcpSchema } from '@/lib/api/contracts/knowledge/mcp'
import { OrchestrationError } from '@/lib/core/orchestration/types'
import { knowledgeOperations } from '@/lib/knowledge/application/operations'
import {
KNOWLEDGE_MCP_READ_ONLY,
Expand All @@ -17,12 +18,6 @@ interface ListMyActivityToolContext {
request: NextRequest
}

/**
* Provider reads one call makes, for the rate limit: about one listing per connected source,
* which is more than a single search's share.
*/
const LIST_MY_ACTIVITY_COST = 2

/**
* Registers `list_my_activity`: what the caller did across their connected sources in a window,
* newest first, with a status per source that names the ones to connect.
Expand All @@ -36,7 +31,7 @@ export function registerListMyActivityTool(
{
title: 'List my activity',
description:
'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.',
'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.',
inputSchema: listMyActivityMcpSchema,
annotations: KNOWLEDGE_MCP_READ_ONLY,
},
Expand All @@ -45,16 +40,28 @@ export function registerListMyActivityTool(
'list_my_activity',
knowledgeOperations.listActivity,
extra.signal,
async (registry, signal) => {
async (registry, signal, charge) => {
const parsed = listMyActivityMcpSchema.parse(input)
const result = await listMyActivity.execute({
principal,
input: { ...parsed, organizationId, resultSecretRegistry: registry, signal },
input: {
...parsed,
organizationId,
resultSecretRegistry: registry,
signal,
/**
* Each account is a separate provider listing: beyond the one operation the call
* was admitted with, one more per further account, admitted before any is read.
*/
admitReads: async (accounts) => {
const rejected = await charge(accounts - 1)
if (rejected) throw new OrchestrationError('unavailable', rejected)
},
},
request,
})
return projectResult(result, registry)
},
LIST_MY_ACTIVITY_COST
}
)
)
}
26 changes: 16 additions & 10 deletions apps/sim/lib/knowledge/mcp/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,14 @@ interface KnowledgeMcpContext {
listMyActivity?: boolean
}

/** What a caller is told when the rate limit refuses a call, with when to retry if known. */
function rateLimitMessage(limited: Response): string {
const retryAfter = parseRetryAfter(limited.headers.get('Retry-After'), Number.MAX_SAFE_INTEGER)
return retryAfter === null
? 'API rate limit exceeded. Please try again later.'
: `API rate limit exceeded. Retry in ${Math.ceil(retryAfter / 1000)} seconds.`
}

/** A request owns its server; no credential or principal survives into another HTTP request. */
export function createKnowledgeMcpServer(context: KnowledgeMcpContext): McpServer {
const { request, auth, organizationId } = context
Expand All @@ -71,17 +79,15 @@ export function createKnowledgeMcpServer(context: KnowledgeMcpContext): McpServe
signal.throwIfAborted()
if (limited) {
outcome = 'rate_limited'
const retryAfter = parseRetryAfter(
limited.headers.get('Retry-After'),
Number.MAX_SAFE_INTEGER
)
return toolError(
retryAfter === null
? 'API rate limit exceeded. Please try again later.'
: `API rate limit exceeded. Retry in ${Math.ceil(retryAfter / 1000)} seconds.`
)
return toolError(rateLimitMessage(limited))
}
const result = await run(new ResolvedSecretTraceRegistry(), signal)
const result = await run(new ResolvedSecretTraceRegistry(), signal, async (more) => {
if (more <= 0) return undefined
const rejected = await v2RateLimits.publicApi.enforce(request, auth, operation, more)

@cubic-dev-ai cubic-dev-ai Bot Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: A cancelled activity call can still consume the per-account budget here even though its provider reads never run. Check signal.throwIfAborted() before dynamic admission and again after it resolves.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At apps/sim/lib/knowledge/mcp/server.ts, line 86:

<comment>A cancelled activity call can still consume the per-account budget here even though its provider reads never run. Check `signal.throwIfAborted()` before dynamic admission and again after it resolves.</comment>

<file context>
@@ -71,17 +79,15 @@ export function createKnowledgeMcpServer(context: KnowledgeMcpContext): McpServe
-      const result = await run(new ResolvedSecretTraceRegistry(), signal)
+      const result = await run(new ResolvedSecretTraceRegistry(), signal, async (more) => {
+        if (more <= 0) return undefined
+        const rejected = await v2RateLimits.publicApi.enforce(request, auth, operation, more)
+        if (!rejected) return undefined
+        outcome = 'rate_limited'
</file context>
Suggested change
const rejected = await v2RateLimits.publicApi.enforce(request, auth, operation, more)
signal.throwIfAborted()
const rejected = await v2RateLimits.publicApi.enforce(request, auth, operation, more)
signal.throwIfAborted()
Fix with cubic

if (!rejected) return undefined
outcome = 'rate_limited'
return rateLimitMessage(rejected)
})
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
outcome = signal.aborted ? 'cancelled' : result.isError ? 'error' : 'success'
resultChars = resultCharacters(result)
return result
Expand Down
10 changes: 9 additions & 1 deletion apps/sim/lib/knowledge/mcp/tool-runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,15 @@ export type KnowledgeMcpToolRunner = (
toolName: SearchMcpActivityInput['toolName'],
operation: ApplicationOperation,
toolSignal: AbortSignal,
run: (registry: ResolvedSecretTraceRegistry, signal: AbortSignal) => Promise<CallToolResult>,
run: (
registry: ResolvedSecretTraceRegistry,
signal: AbortSignal,
/**
* Admits further operations for a call whose size is known only once it runs, before it does
* that work. Resolves to the rate-limit message when the budget cannot cover them.
*/
charge: (cost: number) => Promise<string | undefined>
) => Promise<CallToolResult>,
/** Operations the call performs for the rate limit, such as each document a batched read reads. */
cost?: number
) => Promise<CallToolResult>
Expand Down
2 changes: 1 addition & 1 deletion apps/sim/lib/mothership/chat/citation-evidence.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ export function toCitationResult(
if (toolName === 'list_my_activity' && typeof result.documentName !== 'string')
return {
citationId: result.citationId,
citationUrl: result.citationUrl,
citationUrl: result.url,
documentName: result.title,
connectorType: result.source,
sourceDate: result.timestamp,
Expand Down
45 changes: 33 additions & 12 deletions apps/sim/lib/mothership/generated/sim-assistant-tools.generated.ts
Original file line number Diff line number Diff line change
Expand Up @@ -398,7 +398,7 @@ export const listMyActivityInputFieldsSchema = z
.max(40_000)
.optional()
.describe(
'nextCursor from the previous page, with the same startDate, endDate, source and topK. Pages continue newest first without gaps.'
'nextCursor from the previous page, with the same startDate, endDate and source; topK may change. Pages continue newest first without gaps.'
),
})
.strict()
Expand Down Expand Up @@ -457,7 +457,6 @@ const activityActionSchema = z.enum([
'replied',
'attended',
'assigned',
'mentioned',
])
export type ActivityAction = z.output<typeof activityActionSchema>

Expand All @@ -466,15 +465,12 @@ const activityItemSchema = z.object({
documentId: z.string(),
timestamp: z.string(),
source: liveSearchProviderSchema,
accountId: z.string(),
action: activityActionSchema,
title: z.string(),
url: z.string().nullable(),
container: z.string().optional(),
collaborators: z.array(z.string()),
snippet: z.string(),
/** The timestamp is the item's last update, possibly by someone else, not the person's action. */
approximateTime: z.literal(true).optional(),
})

const listMyActivityResultSchema = z.object({
Expand All @@ -493,6 +489,10 @@ export type ListMyActivityResult = z.output<typeof listMyActivityResultSchema>
* 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.
*/
function peopleFieldFilter(description: string) {
return z.string().trim().min(1).max(200).optional().describe(description)
}

export const searchPeopleInputSchema = z
.object({
query: z
Expand All @@ -512,18 +512,39 @@ export const searchPeopleInputSchema = z
.describe(
'A personId from an earlier result, to show that person with their managers and direct reports. Used instead of query.'
),
name: peopleFieldFilter('Only people whose name contains this text.'),
email: z
.string()
.trim()
.min(3)
.max(320)
.optional()
.describe('Only the person with this exact email address.'),
title: peopleFieldFilter('Only people whose title contains this text.'),
department: peopleFieldFilter('Only people whose department contains this text.'),
location: peopleFieldFilter('Only people whose location contains this text.'),
managerPersonId: z
.string()
.min(1)
.max(255)
.optional()
.describe('Only the direct reports of this personId.'),
cursor: z
.string()
.min(1)
.max(1024)
.optional()
.describe('nextCursor from the previous page of the same query.'),
.describe('nextCursor from the previous page of the same query and filters.'),
})
.strict()
.refine((input) => !input.personId || (input.query === undefined && !input.cursor), {
path: ['personId'],
message: 'Pass either personId or a query with its cursor, not both.',
})
.refine(
({ personId, ...listing }) =>
!personId || Object.values(listing).every((value) => value === undefined),
{
path: ['personId'],
message: 'Pass either personId or a query with its filters and cursor, not both.',
}
)

/**
* The caller's own questions to Sim over a window, oldest first. The 92-day window and the page
Expand Down Expand Up @@ -634,7 +655,7 @@ export const assistantToolContracts = [
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.',
'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.',
inputSchema: searchPeopleInputSchema,
},
{
Expand All @@ -648,7 +669,7 @@ export const assistantToolContracts = [
id: 'list_my_activity',
route: 'sim',
description:
'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.',
'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.',
inputSchema: listMyActivityInputSchema,
},
{
Expand Down
Loading
Loading