Skip to content

Commit bb54718

Browse files
committed
feat(search-mcp): chat continues a conversation by chatId
1 parent 1394733 commit bb54718

4 files changed

Lines changed: 288 additions & 19 deletions

File tree

‎apps/sim/lib/api/contracts/knowledge/mcp.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,5 +113,11 @@ export const chatSearchMcpSchema = workspaceSearchFiltersSchema
113113
.extend({
114114
...mcpDateFilterFields,
115115
query: z.string().trim().min(1, 'A question is required').max(8192),
116+
chatId: z
117+
.string()
118+
.min(1)
119+
.max(64)
120+
.optional()
121+
.describe('The chatId of an earlier chat answer, to ask a follow-up in that conversation.'),
116122
})
117123
.strict()
Lines changed: 209 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,209 @@
1+
/**
2+
* Search MCP chat follow-ups against real PostgreSQL and Redis: which conversation a chatId
3+
* resumes, the per-conversation stream lock, and the transcript a turn leaves behind are
4+
* production code. Authorization, billing, the payload builder and the worker lifecycle are
5+
* stood in, since only conversation ownership, locking and persistence are under test.
6+
*/
7+
import { createDeferred } from '@sim/testing/helpers/deferred'
8+
import { billingAttributionMock } from '@sim/testing/mocks/billing-attribution.mock'
9+
import { knowledgeAvailabilityMock } from '@sim/testing/mocks/knowledge-availability.mock'
10+
import {
11+
mothershipChatPayloadMock,
12+
mothershipChatPayloadMockFns,
13+
} from '@sim/testing/mocks/mothership-chat-payload.mock'
14+
import {
15+
mothershipHeadlessLifecycleMock,
16+
mothershipHeadlessLifecycleMockFns,
17+
} from '@sim/testing/mocks/mothership-headless-lifecycle.mock'
18+
import {
19+
organizationAuthorizationMock,
20+
organizationAuthorizationMockFns,
21+
} from '@sim/testing/mocks/organization-authorization.mock'
22+
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
23+
24+
vi.mock('@/lib/core/application/organization-authorization', () => organizationAuthorizationMock)
25+
vi.mock('@/lib/knowledge/access/availability', () => knowledgeAvailabilityMock)
26+
vi.mock('@/lib/billing/core/attribution', () => billingAttributionMock)
27+
vi.mock('@/lib/mothership/application/load-search-integrations', () => ({
28+
loadCopilotSearchIntegrations: async () => '{"connections":[],"available":[]}',
29+
}))
30+
vi.mock('@/lib/mothership/chat/payload', () => mothershipChatPayloadMock)
31+
vi.mock('@/lib/mothership/request/lifecycle/headless', () => mothershipHeadlessLifecycleMock)
32+
vi.mock('@/lib/mothership/request/session/explicit-abort', () => ({
33+
requestExplicitStreamAbort: async () => undefined,
34+
}))
35+
36+
import type { OAuthAccessTokenPrincipal } from '@sim/auth/principal'
37+
import { db } from '@sim/db'
38+
import { copilotChats, copilotMessages, organization, user } from '@sim/db/schema'
39+
import { generateId } from '@sim/utils/id'
40+
import { and, eq, inArray, isNull } from 'drizzle-orm'
41+
import { organizationSearchChat } from '@/lib/knowledge/application/chat'
42+
import type { OrchestratorResult } from '@/lib/mothership/request/types'
43+
import { ResolvedSecretTraceRegistry } from '@/executor/utils/resolved-secret-trace-registry'
44+
45+
const { mockRunHeadlessCopilotLifecycle } = mothershipHeadlessLifecycleMockFns
46+
const memberId = generateId()
47+
const otherMemberId = generateId()
48+
const organizationId = generateId()
49+
const otherOrganizationId = generateId()
50+
51+
function principalFor(userId: string): OAuthAccessTokenPrincipal {
52+
return {
53+
kind: 'oauth_access_token',
54+
userId,
55+
clientId: 'mcp-client',
56+
tokenId: generateId(),
57+
scopes: ['search:read'],
58+
expiresAt: new Date(Date.now() + 3_600_000),
59+
}
60+
}
61+
62+
function answer(content: string): OrchestratorResult {
63+
return { success: true, content, contentBlocks: [], toolCalls: [] }
64+
}
65+
66+
function ask(query: string, chatId?: string, userId = memberId) {
67+
return organizationSearchChat.execute({
68+
principal: principalFor(userId),
69+
input: {
70+
organizationId,
71+
query,
72+
...(chatId ? { chatId } : {}),
73+
resultSecretRegistry: new ResolvedSecretTraceRegistry(),
74+
},
75+
})
76+
}
77+
78+
async function transcript(chatId: string) {
79+
return db
80+
.select({ id: copilotMessages.id })
81+
.from(copilotMessages)
82+
.where(eq(copilotMessages.chatId, chatId))
83+
}
84+
85+
async function liveChats(userId: string) {
86+
return db
87+
.select({ id: copilotChats.id })
88+
.from(copilotChats)
89+
.where(and(eq(copilotChats.userId, userId), isNull(copilotChats.deletedAt)))
90+
}
91+
92+
describe('Search MCP chat follow-ups', () => {
93+
beforeAll(async () => {
94+
const now = new Date()
95+
await db.insert(user).values(
96+
[memberId, otherMemberId].map((id) => ({
97+
id,
98+
name: 'Search chat fixture',
99+
email: `${id}@search-chat.test`,
100+
emailVerified: true,
101+
createdAt: now,
102+
updatedAt: now,
103+
}))
104+
)
105+
await db.insert(organization).values(
106+
[organizationId, otherOrganizationId].map((id) => ({
107+
id,
108+
name: 'Search chat fixture',
109+
slug: `search-chat-${id}`,
110+
}))
111+
)
112+
mothershipChatPayloadMockFns.mockBuildCopilotRequestPayload.mockResolvedValue({
113+
mode: 'assistant',
114+
})
115+
})
116+
117+
afterAll(async () => {
118+
await db.delete(copilotChats).where(inArray(copilotChats.userId, [memberId, otherMemberId]))
119+
await db
120+
.delete(organization)
121+
.where(inArray(organization.id, [organizationId, otherOrganizationId]))
122+
await db.delete(user).where(inArray(user.id, [memberId, otherMemberId]))
123+
})
124+
125+
beforeEach(() => {
126+
mockRunHeadlessCopilotLifecycle.mockReset()
127+
organizationAuthorizationMockFns.mockAuthorizeOrganizationOperation.mockImplementation(
128+
async (principal: OAuthAccessTokenPrincipal) => ({
129+
userId: principal.userId,
130+
organizationId,
131+
})
132+
)
133+
})
134+
135+
it('continues the caller’s conversation with the same chat and transcript', async () => {
136+
mockRunHeadlessCopilotLifecycle.mockResolvedValueOnce(answer('The kit is in the suitcase.'))
137+
const first = await ask('Where is the field kit?')
138+
if (!first.chatId) throw new Error('Expected a saved conversation')
139+
140+
mockRunHeadlessCopilotLifecycle.mockResolvedValueOnce(answer('It is violet.'))
141+
const followUp = await ask('What colour is it?', first.chatId)
142+
143+
expect(followUp.chatId).toBe(first.chatId)
144+
expect(mockRunHeadlessCopilotLifecycle).toHaveBeenLastCalledWith(
145+
expect.anything(),
146+
expect.objectContaining({ chatId: first.chatId })
147+
)
148+
expect(await transcript(first.chatId)).toHaveLength(4)
149+
expect(await liveChats(memberId)).toEqual([{ id: first.chatId }])
150+
})
151+
152+
it.each([
153+
['another member’s conversation', 'other-member'],
154+
['a conversation in another organization', 'other-organization'],
155+
['a deleted conversation', 'deleted'],
156+
['an Agent conversation', 'agent'],
157+
['a value that is not a chat ID', 'malformed'],
158+
])('refuses %s as not found before running anything', async (_case, kind) => {
159+
const chatId = generateId()
160+
if (kind !== 'malformed')
161+
await db.insert(copilotChats).values({
162+
id: chatId,
163+
userId: kind === 'other-member' ? otherMemberId : memberId,
164+
organizationId: kind === 'other-organization' ? otherOrganizationId : organizationId,
165+
type: 'mothership',
166+
...(kind === 'deleted' ? { deletedAt: new Date() } : {}),
167+
...(kind === 'agent' ? { config: { conversationMode: 'agent' } } : {}),
168+
})
169+
await expect(
170+
ask('Follow up', kind === 'malformed' ? 'not-a-chat' : chatId)
171+
).rejects.toMatchObject({ code: 'not_found' })
172+
expect(mockRunHeadlessCopilotLifecycle).not.toHaveBeenCalled()
173+
})
174+
175+
it('refuses a follow-up while the conversation is still answering', async () => {
176+
mockRunHeadlessCopilotLifecycle.mockResolvedValueOnce(answer('First answer.'))
177+
const { chatId } = await ask('First question')
178+
if (!chatId) throw new Error('Expected a saved conversation')
179+
180+
const running = createDeferred<OrchestratorResult>()
181+
const started = createDeferred<void>()
182+
mockRunHeadlessCopilotLifecycle.mockImplementationOnce(async () => {
183+
started.resolve()
184+
return running.promise
185+
})
186+
const inFlight = ask('Second question', chatId)
187+
await started.promise
188+
189+
await expect(ask('Third question', chatId)).rejects.toMatchObject({ code: 'conflict' })
190+
running.resolve(answer('Second answer.'))
191+
await expect(inFlight).resolves.toMatchObject({ chatId })
192+
193+
mockRunHeadlessCopilotLifecycle.mockResolvedValueOnce(answer('Third answer.'))
194+
await expect(ask('Third question', chatId)).resolves.toMatchObject({ chatId })
195+
expect(await transcript(chatId)).toHaveLength(6)
196+
})
197+
198+
it('keeps a resumed conversation when its follow-up fails', async () => {
199+
mockRunHeadlessCopilotLifecycle.mockResolvedValueOnce(answer('First answer.'))
200+
const { chatId } = await ask('First question')
201+
if (!chatId) throw new Error('Expected a saved conversation')
202+
203+
mockRunHeadlessCopilotLifecycle.mockResolvedValueOnce({ ...answer(''), success: false })
204+
await expect(ask('Second question', chatId)).rejects.toThrow('could not finish')
205+
206+
expect(await liveChats(memberId)).toContainEqual({ id: chatId })
207+
expect(await transcript(chatId)).toHaveLength(2)
208+
})
209+
})

‎apps/sim/lib/knowledge/application/chat.ts‎

Lines changed: 70 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,10 @@ import type { Principal } from '@sim/auth/principal'
22
import { db } from '@sim/db'
33
import { copilotChats, copilotMessages } from '@sim/db/schema'
44
import { createLogger } from '@sim/logger'
5-
import { generateId } from '@sim/utils/id'
5+
import { generateId, isValidUuid } from '@sim/utils/id'
66
import { isPlainRecord } from '@sim/utils/object'
77
import { truncate } from '@sim/utils/string'
8-
import { and, eq, isNull, notExists } from 'drizzle-orm'
8+
import { and, eq, isNull, notExists, sql } from 'drizzle-orm'
99
import {
1010
type WorkspaceSearchFilters,
1111
workspaceSearchFiltersSchema,
@@ -23,6 +23,7 @@ import {
2323
} from '@/lib/knowledge/application/chat-citations'
2424
import { organizationSearchChatOperation } from '@/lib/knowledge/application/chat-operations'
2525
import { loadCopilotSearchIntegrations } from '@/lib/mothership/application/load-search-integrations'
26+
import { conversationModeSelection } from '@/lib/mothership/chat/intent'
2627
import { persistCopilotChatTurn } from '@/lib/mothership/chat/messages-store'
2728
import { buildCopilotRequestPayload } from '@/lib/mothership/chat/payload'
2829
import {
@@ -34,6 +35,10 @@ import {
3435
} from '@/lib/mothership/chat/persisted-message'
3536
import { MOTHERSHIP_CHAT_DEFAULT_MODEL } from '@/lib/mothership/constants'
3637
import { runHeadlessCopilotLifecycle } from '@/lib/mothership/request/lifecycle/headless'
38+
import {
39+
acquirePendingChatStream,
40+
releasePendingChatStream,
41+
} from '@/lib/mothership/request/session/abort'
3742
import { requestExplicitStreamAbort } from '@/lib/mothership/request/session/explicit-abort'
3843
import {
3944
isResolvedSecretModelContentUnchanged,
@@ -48,6 +53,8 @@ const SEARCH_CHAT_TIMEOUT_MS = 180_000
4853
export interface OrganizationSearchChatInput {
4954
organizationId: string
5055
query: string
56+
/** A conversation this caller started here earlier, continued with its history. */
57+
chatId?: string
5158
filters?: WorkspaceSearchFilters
5259
resultSecretRegistry: ResolvedSecretTraceRegistry
5360
signal?: AbortSignal
@@ -80,7 +87,54 @@ async function authorize(principal: Principal, organizationId: string) {
8087
return context
8188
}
8289

83-
/** Runs the existing organization Assistant in a new private conversation for this caller. */
90+
const CONVERSATION_NOT_FOUND =
91+
'Conversation not found. Ask without chatId to start a new conversation.'
92+
93+
/**
94+
* The caller's own live Assistant conversation in this organization, as {@link createConversation}
95+
* makes them, or undefined. Another member's chat, a deleted one, and an Agent or Plan chat, whose
96+
* turns need permissions this surface does not grant, are all not found alike.
97+
*/
98+
async function findConversation(chatId: string, userId: string, organizationId: string) {
99+
if (!isValidUuid(chatId)) return undefined
100+
const [chat] = await db
101+
.select({ id: copilotChats.id })
102+
.from(copilotChats)
103+
.where(
104+
and(
105+
eq(copilotChats.id, chatId),
106+
eq(copilotChats.userId, userId),
107+
eq(copilotChats.organizationId, organizationId),
108+
eq(copilotChats.type, 'mothership'),
109+
isNull(copilotChats.deletedAt),
110+
sql`${conversationModeSelection} = 'assistant'`
111+
)
112+
)
113+
.limit(1)
114+
return chat
115+
}
116+
117+
async function createConversation(userId: string, organizationId: string, query: string) {
118+
const [chat] = await db
119+
.insert(copilotChats)
120+
.values({
121+
userId,
122+
organizationId,
123+
type: 'mothership',
124+
model: MOTHERSHIP_CHAT_DEFAULT_MODEL,
125+
title: truncate(query.replace(/\s+/g, ' '), 80),
126+
lastSeenAt: new Date(),
127+
})
128+
.returning({ id: copilotChats.id })
129+
if (!chat) throw new OrchestrationError('internal', 'Unable to create a Search conversation')
130+
return chat
131+
}
132+
133+
/**
134+
* Runs the existing organization Assistant for this caller: in a new private conversation, or as
135+
* a follow-up in one of the caller's own conversations, whose earlier turns the Assistant reads.
136+
* One question at a time holds a conversation; a follow-up sent while it answers is refused.
137+
*/
84138
export const organizationSearchChat: OperationUseCase<
85139
typeof organizationSearchChatOperation,
86140
OrganizationSearchChatInput,
@@ -110,21 +164,19 @@ export const organizationSearchChat: OperationUseCase<
110164
organizationId,
111165
})
112166
input.signal?.throwIfAborted()
113-
const [chat] = await db
114-
.insert(copilotChats)
115-
.values({
116-
userId,
117-
organizationId,
118-
type: 'mothership',
119-
model: MOTHERSHIP_CHAT_DEFAULT_MODEL,
120-
title: truncate(query.replace(/\s+/g, ' '), 80),
121-
lastSeenAt: new Date(),
122-
})
123-
.returning({ id: copilotChats.id })
124-
if (!chat) throw new OrchestrationError('internal', 'Unable to create a Search conversation')
167+
const resumed = input.chatId !== undefined
168+
const chat = resumed
169+
? await findConversation(input.chatId ?? '', userId, organizationId)
170+
: await createConversation(userId, organizationId, query)
171+
if (!chat) throw new OrchestrationError('not_found', CONVERSATION_NOT_FOUND)
125172

126173
const chatId = chat.id
127174
const messageId = generateId()
175+
if (!(await acquirePendingChatStream(chatId, messageId, 0)))
176+
throw new OrchestrationError(
177+
'conflict',
178+
'This conversation is still answering an earlier question. Wait for that answer, then ask again.'
179+
)
128180
const controller = new AbortController()
129181
let running = false
130182
let persisted = false
@@ -228,7 +280,9 @@ export const organizationSearchChat: OperationUseCase<
228280
clearTimeout(timeout)
229281
input.signal?.removeEventListener('abort', abort)
230282
await explicitAbort
231-
if (!persisted) {
283+
await releasePendingChatStream(chatId, messageId)
284+
/** A resumed conversation keeps its history whatever this turn did. */
285+
if (!persisted && !resumed) {
232286
/** Retain run diagnostics, but keep an unsuccessful empty conversation out of history. */
233287
try {
234288
await db.transaction(async (tx) => {

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

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -341,7 +341,7 @@ export function createKnowledgeMcpServer(context: KnowledgeMcpContext): McpServe
341341
{
342342
title: 'Chat',
343343
description:
344-
'Ask the Sim Assistant to research a question in your accessible organization sources and write a cited answer. It runs its own multi-step search, so it usually takes 30 to 60 seconds and returns a synthesized answer rather than the sources. To answer a question yourself, use search and read_document, which return sources in seconds; use chat only when the user asks for the Sim Assistant’s answer. Starts a new private conversation. Use source, modifiedAfter, or documentIds to narrow the evidence. It searches the public web only when your sources lack the answer, and makes no source changes.',
344+
'Ask the Sim Assistant to research a question in your accessible organization sources and write a cited answer. It runs its own multi-step search, so it usually takes 30 to 60 seconds and returns a synthesized answer rather than the sources. To answer a question yourself, use search and read_document, which return sources in seconds; use chat only when the user asks for the Sim Assistant’s answer. Starts a new private conversation and returns its chatId; pass that chatId with the next question to ask a follow-up that builds on the earlier answers. Use source, modifiedAfter, or documentIds to narrow the evidence. It searches the public web only when your sources lack the answer, and makes no source changes.',
345345
inputSchema: chatSearchMcpSchema,
346346
annotations: {
347347
readOnlyHint: false,
@@ -350,12 +350,12 @@ export function createKnowledgeMcpServer(context: KnowledgeMcpContext): McpServe
350350
openWorldHint: true,
351351
},
352352
},
353-
async ({ query, ...filters }, extra) =>
353+
async ({ query, chatId, ...filters }, extra) =>
354354
execute('chat', organizationSearchChatOperation, extra.signal, async (registry, signal) => {
355355
const { organizationSearchChat } = await import('@/lib/knowledge/application/chat')
356356
const result = await organizationSearchChat.execute({
357357
principal,
358-
input: { organizationId, query, filters, resultSecretRegistry: registry, signal },
358+
input: { organizationId, query, chatId, filters, resultSecretRegistry: registry, signal },
359359
})
360360
return projectResult(result, registry)
361361
})

0 commit comments

Comments
 (0)