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
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,7 @@ export const TOOL_ICONS: Readonly<Record<string, IconComponent>> = {
search_sources: Search,
settings: Settings,
list_workspaces: Search,
list_my_activity: Search,
workspaces: Search,
set_block_enabled: Pencil,
set_environment_variables: Settings,
Expand Down
11 changes: 11 additions & 0 deletions apps/sim/lib/api/contracts/knowledge/mcp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ import {
} from '@/lib/api/contracts/knowledge/search'
import { mcpJsonRpcMessageSchema } from '@/lib/api/contracts/mcp'
import {
listMyActivityInputFieldsSchema,
readDocumentInputSchema,
refineActivityWindow,
refineSearchWorkspaceInput,
searchWorkspaceInputFieldsSchema,
} from '@/lib/api/contracts/mothership-assistant-tools'
Expand Down Expand Up @@ -64,6 +66,15 @@ export const liveSearchMcpSchema = searchWorkspaceInputFieldsSchema
.strict()
.superRefine(refineSearchWorkspaceInput)

/** list_my_activity as the Search MCP presents it: a date without an offset reads as UTC. */
export const listMyActivityMcpSchema = listMyActivityInputFieldsSchema
.extend({
startDate: mcpDateFilter(listMyActivityInputFieldsSchema.shape.startDate),
endDate: mcpDateFilter(listMyActivityInputFieldsSchema.shape.endDate),
})
.strict()
.superRefine(refineActivityWindow)

/**
* Previews a search returns when the caller sets no topK. A query across every source shares one
* list among all of them, so it gets more room than a search of one source, a native query, or a
Expand Down
138 changes: 138 additions & 0 deletions apps/sim/lib/api/contracts/mothership-assistant-tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -335,6 +335,137 @@ export const readDocumentInputSchema = z.object({
),
})

/** Days one activity listing may span, about a quarter. */
export const MAX_ACTIVITY_WINDOW_DAYS = 92
/** Activity entries one page returns when the caller sets no topK. */
export const DEFAULT_ACTIVITY_TOP_K = 25

/** The activity filters, shared by every surface; refine with {@link refineActivityWindow}. */
export const listMyActivityInputFieldsSchema = z
.object({
startDate: z
.string()
.datetime({ offset: true })
.optional()
.describe(
`Inclusive start of the window, an ISO datetime with the user’s timezone offset. Defaults to 7 days before endDate; the window spans at most ${MAX_ACTIVITY_WINDOW_DAYS} days.`
),
endDate: z
.string()
.datetime({ offset: true })
.optional()
.describe(
'Exclusive end of the window, an ISO datetime with the user’s timezone offset. Defaults to now; a later time reads up to now. For whole days, use local midnight after the final day.'
),
source: liveSearchProviderSchema
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
.optional()
.describe(
'One source to read, such as slack, gmail, google_calendar, jira or confluence. Omit for every connected source.'
),
topK: z
.number()
.int()
.min(1)
.max(50)
.optional()
.describe(`Maximum entries on this page: ${DEFAULT_ACTIVITY_TOP_K} by default.`),
cursor: z
.string()
.min(1)
.max(40_000)
.optional()
.describe(
'nextCursor from the previous page, with the same startDate, endDate, source and topK. Pages continue newest first without gaps.'
),
})
.strict()

/** Rules shared by every activity input schema built from {@link listMyActivityInputFieldsSchema}. */
export function refineActivityWindow(
input: { startDate?: string; endDate?: string; cursor?: string },
context: z.RefinementCtx
) {
/** A continuation reads the window its signed cursor fixed, however long ago that was. */
if (!input.startDate || !input.endDate || input.cursor) return
const start = Date.parse(input.startDate)
const end = Date.parse(input.endDate)
if (start >= end)
context.addIssue({
code: 'custom',
path: ['endDate'],
message: 'endDate must be after startDate.',
})
/** A later endDate reads up to now, so the span counts only up to now. */ else if (
Math.min(end, Date.now()) - start >
MAX_ACTIVITY_WINDOW_DAYS * 86_400_000
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
)
context.addIssue({
code: 'custom',
path: ['startDate'],
message: `The window spans at most ${MAX_ACTIVITY_WINDOW_DAYS} days.`,
})
}

export const listMyActivityInputSchema =
listMyActivityInputFieldsSchema.superRefine(refineActivityWindow)

/**
* How one source served a multi-source result. `not_connected` and `reconnect` carry `connect`:
* the provider to connect and the page where the caller connects it.
*/
const liveSourceStatusSchema = z.object({
source: liveSearchProviderSchema,
accountId: z.string().optional(),
displayName: z.string().optional(),
status: z.enum(['ok', 'partial', 'not_connected', 'reconnect', 'unsupported', 'failed']),
reason: z.enum(['rate_limited', 'timeout', 'unavailable']).optional(),
retryAfterSeconds: z.number().optional(),
message: z.string().optional(),
connect: z.object({ providerId: z.string(), url: z.string() }).optional(),
})
export type LiveSourceStatus = z.output<typeof liveSourceStatusSchema>

/** What the person did to an item, as one activity entry reports it. */
const activityActionSchema = z.enum([
'created',
'edited',
'commented',
'sent',
'replied',
'attended',
'assigned',
'mentioned',
])
export type ActivityAction = z.output<typeof activityActionSchema>

const activityItemSchema = z.object({
/** Reads the item with read_document. */
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({
window: z.object({ startDate: z.string(), endDate: z.string() }),
items: z.array(activityItemSchema),
/** More entries remain; continue with nextCursor. */
truncated: z.boolean(),
nextCursor: z.string().optional(),
/** `complete` when every connected source that reports activity was read in full. */
coverage: z.enum(['complete', 'partial']),
sources: z.array(liveSourceStatusSchema.extend({ itemCount: z.number().int().min(0) })),
})
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.
Expand Down Expand Up @@ -490,6 +621,13 @@ export const assistantToolContracts = [
'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.',
inputSchema: listMyChatHistoryInputSchema,
},
{
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.',
inputSchema: listMyActivityInputSchema,
},
{
id: 'oauth_get_auth_link',
route: 'sim',
Expand Down
1 change: 1 addition & 0 deletions apps/sim/lib/core/config/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -627,6 +627,7 @@ export const env = createEnv({
CHANGELOG: z.boolean().optional(), // Fallback for the `changelog` feature flag off AppConfig
SIM_LINKS: z.boolean().optional(), // Fallback for the `sim-links` feature flag off AppConfig
PEOPLE: z.boolean().optional(), // Fallback for the `people` feature flag off AppConfig
MY_ACTIVITY: z.boolean().optional(), // Fallback for the `my-activity` feature flag off AppConfig
ORGANIZATION_ACTIVITY_ROLLUP_READS: z.boolean().optional(), // Fallback for the `organization-activity-rollup-reads` feature flag off AppConfig
ACTIVITY_ROLLUP_MAINTENANCE: z.boolean().optional(), // Fallback for the `activity-rollup-maintenance` feature flag off AppConfig
ACTIVITY_ROLLUP_BACKFILL_ROWS_PER_SECOND: z.coerce.number().int().positive().optional(), // Source rows the activity rollup backfill reads per second (default 20000)
Expand Down
6 changes: 6 additions & 0 deletions apps/sim/lib/core/config/feature-flags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,12 @@ const FEATURE_FLAGS = {
'Enable the organization People directory, org chart, profile imports, and directory sync. Supports organization rollout; disabled by default.',
fallback: 'PEOPLE',
},
'my-activity': {
description:
"Enable list_my_activity: the caller's own activity across their connected sources, in the " +
'Search MCP and the organization Assistant. Supports organization rollout; disabled by default.',
fallback: 'MY_ACTIVITY',
},
'mothership-model-selector': {
description:
'Show the Mothership model selector, model-specific effort levels, and Fast for supported ' +
Expand Down
17 changes: 17 additions & 0 deletions apps/sim/lib/knowledge/application/operations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -420,6 +420,23 @@ export const knowledgeOperations = {
}),
{ organizationDelegatedServices: ['copilot', 'slack-search', 'executor'] }
),
/**
* The caller's own activity across their connected sources. It always reads the person the
* principal represents, so a principal without one (a workspace API key, an actorless run) is
* refused rather than read as anyone else.
*/
listActivity: defineKnowledgeOperation(
defineWorkspaceOperation({
id: 'knowledge.activity.list',
oauthScope: 'search:read',
minimumRole: 'read',
workspaceApiKey: 'deny',
capability: 'knowledge.use',
contentDelivery: 'sourced',
...HUMAN_AND_COPILOT_PRINCIPAL_POLICY,
}),
{ organizationDelegation: 'allow', organizationDelegatedServices: ['copilot', 'executor'] }
),
listFolders: defineKnowledgeOperation(
defineWorkspaceOperation({
id: 'knowledge.folders.list',
Expand Down
60 changes: 60 additions & 0 deletions apps/sim/lib/knowledge/mcp/my-activity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
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 { knowledgeOperations } from '@/lib/knowledge/application/operations'
import {
KNOWLEDGE_MCP_READ_ONLY,
type KnowledgeMcpToolRunner,
projectResult,
} from '@/lib/knowledge/mcp/tool-runner'
import { listMyActivity } from '@/lib/sim-search/live/activity'

interface ListMyActivityToolContext {
execute: KnowledgeMcpToolRunner
principal: Principal
organizationId: string
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.
*/
export function registerListMyActivityTool(
server: McpServer,
{ execute, principal, organizationId, request }: ListMyActivityToolContext
) {
server.registerTool(
'list_my_activity',
{
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.',
inputSchema: listMyActivityMcpSchema,
annotations: KNOWLEDGE_MCP_READ_ONLY,
},
async (input: unknown, extra: { signal: AbortSignal }) =>
execute(
'list_my_activity',
knowledgeOperations.listActivity,
extra.signal,
async (registry, signal) => {
const parsed = listMyActivityMcpSchema.parse(input)
const result = await listMyActivity.execute({
principal,
input: { ...parsed, organizationId, resultSecretRegistry: registry, signal },
request,
})
return projectResult(result, registry)
},
LIST_MY_ACTIVITY_COST
)
)
}
12 changes: 12 additions & 0 deletions apps/sim/lib/knowledge/mcp/route-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import { createKnowledgeMcpServer } from '@/lib/knowledge/mcp/server'
import { repairToolCallMessage, toolCallInputIssues } from '@/lib/knowledge/mcp/tool-arguments'
import { getSearchMcpUrl } from '@/lib/knowledge/mcp/urls'
import { canLookUpPeople } from '@/lib/people/directory-lookup'
import { isMyActivityEnabled } from '@/lib/sim-search/live/activity'
import { v2CaughtOrchestrationError, v2Error } from '@/app/api/v2/lib/response'

const logger = createLogger('KnowledgeMcp')
Expand All @@ -42,6 +43,16 @@ function mcpAuth(resource: string) {
return mcpCredentialAuth({ resource, allowUnboundApiTokens: true })
}

/**
* Whether this message needs list_my_activity registered: a call to it, which its use case
* authorizes, or a tools/list while the feature is on for this organization.
*/
async function offersListMyActivity(message: Record<string, unknown>, organizationId: string) {
if (message.method === 'tools/call')
return isRecordLike(message.params) && message.params.name === 'list_my_activity'
return message.method === 'tools/list' && isMyActivityEnabled(organizationId)
}

export function createKnowledgeMcpHandlers() {
/** JSON-RPC is a protocol boundary; SDK dispatch calls the same authorized knowledge use cases. */
const handler = withRouteHandler(
Expand Down Expand Up @@ -82,6 +93,7 @@ export function createKnowledgeMcpHandlers() {
auth: admission.auth,
...parsed.data.params,
searchPeople: await offersSearchPeople(message, admission.auth.principal, organizationId),
listMyActivity: await offersListMyActivity(message, organizationId),
})
return await serveStatelessMcp(server, request, message)
} catch (error) {
Expand Down
6 changes: 6 additions & 0 deletions apps/sim/lib/knowledge/mcp/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
type SearchMcpActivityInput,
} from '@/lib/knowledge/mcp/activity'
import { registerListMyChatHistoryTool } from '@/lib/knowledge/mcp/chat-history'
import { registerListMyActivityTool } from '@/lib/knowledge/mcp/my-activity'
import {
callerErrorMessage,
readOrganizationDocuments,
Expand Down Expand Up @@ -49,6 +50,8 @@ interface KnowledgeMcpContext {
auth: V2ApiKeyAuthContext
/** Registers search_people, which its use cases authorize on every call. */
searchPeople?: boolean
/** Registers list_my_activity, which its use case authorizes on every call. */
listMyActivity?: boolean
}

/** A request owns its server; no credential or principal survives into another HTTP request. */
Expand Down Expand Up @@ -206,6 +209,9 @@ export function createKnowledgeMcpServer(context: KnowledgeMcpContext): McpServe
// Only a person has a chat history; a workspace API key acts for no one.
if (resolvePrincipalSubjectUserId(principal))
registerListMyChatHistoryTool(server, { execute, principal, organizationId })
// Activity is always the caller's own; a workspace API key has no person to list.
if (context.listMyActivity && resolvePrincipalSubjectUserId(principal))
registerListMyActivityTool(server, { execute, principal, organizationId, request })

return server
}
10 changes: 10 additions & 0 deletions apps/sim/lib/knowledge/search/citation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,13 @@ import { liveDocumentKey } from '@/lib/sim-search/live/reference'
export function liveCitationId(documentId: string): string {
return `live:${sha256Hex(liveDocumentKey(documentId)).slice(0, 32)}`
}

/**
* The citation ID of one activity entry. Entries that read the same document can link to
* different places in it, such as two comments on one page, so the link is part of the identity.
*/
export function activityCitationId(documentId: string, url: string | null): string {
return url
? `live:${sha256Hex(`${liveDocumentKey(documentId)}\n${url}`).slice(0, 32)}`
: liveCitationId(documentId)
}
1 change: 1 addition & 0 deletions apps/sim/lib/mothership/assistant/tool-policy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export const ASSISTANT_TOOLS = new Set([
'read_document',
'search_people',
'list_my_chat_history',
'list_my_activity',
'oauth_get_auth_link',
'run_function',
])
Expand Down
Loading
Loading