Skip to content

Commit b224e03

Browse files
committed
fix(search): charge Search MCP activity by the accounts a page read, after admission
1 parent b4091c6 commit b224e03

5 files changed

Lines changed: 29 additions & 62 deletions

File tree

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

Lines changed: 16 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,7 @@ import {
88
type KnowledgeMcpToolRunner,
99
projectResult,
1010
} from '@/lib/knowledge/mcp/tool-runner'
11-
import { listMyActivity, MAX_ACTIVITY_ACCOUNTS } from '@/lib/sim-search/live/activity'
12-
import { activityCursorAccountCount } from '@/lib/sim-search/live/activity-page'
13-
import { listLiveSearchAccounts } from '@/lib/sim-search/live/application'
14-
import { supportsActivity } from '@/lib/sim-search/live/providers'
11+
import { listMyActivity } from '@/lib/sim-search/live/activity'
1512

1613
interface ListMyActivityToolContext {
1714
execute: KnowledgeMcpToolRunner
@@ -20,33 +17,6 @@ interface ListMyActivityToolContext {
2017
request: NextRequest
2118
}
2219

23-
/**
24-
* What one call costs against the rate limit: one operation per account it reads, since each is
25-
* a separate provider listing. A lookup that fails charges one, as a call reading nothing would.
26-
*/
27-
async function activityCost(
28-
principal: Principal,
29-
organizationId: string,
30-
source: string | undefined,
31-
cursor: string | undefined
32-
): Promise<number> {
33-
/** A continuation reads only the accounts its cursor still names. */
34-
const continued = cursor ? activityCursorAccountCount(cursor) : undefined
35-
if (continued !== undefined) return Math.min(MAX_ACTIVITY_ACCOUNTS, Math.max(1, continued))
36-
try {
37-
const { accounts } = await listLiveSearchAccounts.execute({
38-
principal,
39-
input: { organizationId },
40-
})
41-
const read = accounts.filter(
42-
(account) => supportsActivity(account.provider) && (!source || account.provider === source)
43-
).length
44-
return Math.min(MAX_ACTIVITY_ACCOUNTS, Math.max(1, read))
45-
} catch {
46-
return 1
47-
}
48-
}
49-
5020
/**
5121
* Registers `list_my_activity`: what the caller did across their connected sources in a window,
5222
* newest first, with a status per source that names the ones to connect.
@@ -64,29 +34,31 @@ export function registerListMyActivityTool(
6434
inputSchema: listMyActivityMcpSchema,
6535
annotations: KNOWLEDGE_MCP_READ_ONLY,
6636
},
67-
async (input: unknown, extra: { signal: AbortSignal }) => {
68-
const requested = listMyActivityMcpSchema.safeParse(input)
69-
const cost = await activityCost(
70-
principal,
71-
organizationId,
72-
requested.data?.source,
73-
requested.data?.cursor
74-
)
75-
return execute(
37+
async (input: unknown, extra: { signal: AbortSignal }) =>
38+
execute(
7639
'list_my_activity',
7740
knowledgeOperations.listActivity,
7841
extra.signal,
79-
async (registry, signal) => {
42+
async (registry, signal, charge) => {
8043
const parsed = listMyActivityMcpSchema.parse(input)
8144
const result = await listMyActivity.execute({
8245
principal,
8346
input: { ...parsed, organizationId, resultSecretRegistry: registry, signal },
8447
request,
8548
})
49+
/**
50+
* Each account read is a separate provider listing, so beyond the one operation the call
51+
* was admitted with, it is charged one per further account this page read.
52+
*/
53+
const accountsRead = result.sources.filter(
54+
({ accountId, status, reason }) =>
55+
accountId &&
56+
status !== 'unsupported' &&
57+
!(status === 'failed' && reason === 'unavailable')
58+
).length
59+
await charge(accountsRead - 1)
8660
return projectResult(result, registry)
87-
},
88-
cost
61+
}
8962
)
90-
}
9163
)
9264
}

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

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,9 @@ export function createKnowledgeMcpServer(context: KnowledgeMcpContext): McpServe
8181
: `API rate limit exceeded. Retry in ${Math.ceil(retryAfter / 1000)} seconds.`
8282
)
8383
}
84-
const result = await run(new ResolvedSecretTraceRegistry(), signal)
84+
const result = await run(new ResolvedSecretTraceRegistry(), signal, async (more) => {
85+
if (more > 0) await v2RateLimits.publicApi.enforce(request, auth, operation, more)
86+
})
8587
outcome = signal.aborted ? 'cancelled' : result.isError ? 'error' : 'success'
8688
resultChars = resultCharacters(result)
8789
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+
* Charges further operations once the call knows what it read, for a call whose size is not
30+
* known before it runs. The call was already admitted, so this only spends the budget.
31+
*/
32+
charge: (cost: number) => Promise<void>
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/sim-search/live/activity-page.ts‎

Lines changed: 0 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -287,18 +287,3 @@ export function readActivityCursor(
287287
return undefined
288288
}
289289
}
290-
291-
/**
292-
* How many accounts a cursor continues, for charging a page before it is read. The cursor is not
293-
* verified here; a forged one is refused when the page reads it.
294-
*/
295-
export function activityCursorAccountCount(value: string): number | undefined {
296-
try {
297-
const parsed = cursorSchema
298-
.pick({ accounts: true })
299-
.safeParse(JSON.parse(Buffer.from(value, 'base64url').toString('utf8')))
300-
return parsed.success ? Object.keys(parsed.data.accounts).length : undefined
301-
} catch {
302-
return undefined
303-
}
304-
}

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ const logger = createLogger('LiveActivity')
5858
const DAY_MS = 86_400_000
5959
const DEFAULT_WINDOW_DAYS = 7
6060
/** Accounts one call reads, as one search does. */
61-
export const MAX_ACTIVITY_ACCOUNTS = 20
61+
const MAX_ACTIVITY_ACCOUNTS = 20
6262
/** Accounts resolving their credential and opening their session at once, as for search. */
6363
const ACCOUNT_OPEN_CONCURRENCY = 6
6464
/** Milliseconds a whole call may take, and one account once it gets a slot, as for search. */

0 commit comments

Comments
 (0)