forked from vercel/ai-chatbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroute.ts
263 lines (230 loc) · 8.57 KB
/
route.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
import {
UIMessage,
appendResponseMessages,
createDataStreamResponse,
smoothStream,
streamText,
experimental_createMCPClient,
} from 'ai';
import { Experimental_StdioMCPTransport } from 'ai/mcp-stdio';
import { auth } from '@/app/(auth)/auth';
import { systemPrompt } from '@/lib/ai/prompts';
import {
deleteChatById,
getChatById,
saveChat,
saveMessages,
getEnabledMcpServersByUserId,
} from '@/lib/db/queries';
import {
generateUUID,
getMostRecentUserMessage,
getTrailingMessageId,
} from '@/lib/utils';
import { generateTitleFromUserMessage } from '../../actions';
import { createDocument } from '@/lib/ai/tools/create-document';
import { updateDocument } from '@/lib/ai/tools/update-document';
import { requestSuggestions } from '@/lib/ai/tools/request-suggestions';
import { getWeather } from '@/lib/ai/tools/get-weather';
import { isProductionEnvironment } from '@/lib/constants';
import { myProvider } from '@/lib/ai/providers';
export const maxDuration = 60;
export async function POST(request: Request) {
let mcpClientsToClose: Awaited<ReturnType<typeof experimental_createMCPClient>>[] = [];
try {
const {
id,
messages,
selectedChatModel,
}: {
id: string;
messages: Array<UIMessage>;
selectedChatModel: string;
} = await request.json();
const session = await auth();
if (!session || !session.user || !session.user.id) {
return new Response('Unauthorized', { status: 401 });
}
const userId = session.user.id;
const userMessage = getMostRecentUserMessage(messages);
if (!userMessage) {
return new Response('No user message found', { status: 400 });
}
const chat = await getChatById({ id });
if (!chat) {
const title = await generateTitleFromUserMessage({
message: userMessage,
});
await saveChat({ id, userId: userId, title });
} else {
if (chat.userId !== userId) {
return new Response('Unauthorized', { status: 401 });
}
}
await saveMessages({
messages: [
{
chatId: id,
id: userMessage.id,
role: 'user',
parts: userMessage.parts,
attachments: userMessage.experimental_attachments ?? [],
createdAt: new Date(),
},
],
});
return createDataStreamResponse({
execute: async (dataStream) => {
try {
const staticTools = {
getWeather,
createDocument: createDocument({ session, dataStream }),
updateDocument: updateDocument({ session, dataStream }),
requestSuggestions: requestSuggestions({
session,
dataStream,
}),
};
let combinedTools: Record<string, any> = { ...staticTools };
try {
const enabledServers = await getEnabledMcpServersByUserId({ userId });
for (const server of enabledServers) {
try {
let transport;
const config = server.config as any;
if (config.transportType === 'sse') {
transport = {
type: 'sse' as const,
url: config.url,
};
} else if (config.transportType === 'stdio') {
if (isProductionEnvironment) {
console.warn(`SECURITY WARNING: Initializing MCP client with stdio transport in production for server: ${server.name} (ID: ${server.id})`);
}
transport = new Experimental_StdioMCPTransport({
command: config.command,
args: config.args || [],
});
} else {
console.warn(`Unsupported MCP transport type '${config.transportType}' for server ${server.name}`);
continue;
}
const mcpClient = await experimental_createMCPClient({ transport });
mcpClientsToClose.push(mcpClient);
const mcpTools = await mcpClient.tools();
combinedTools = { ...combinedTools, ...mcpTools };
console.log(`Loaded ${Object.keys(mcpTools).length} tools from MCP server: ${server.name}`);
} catch (mcpError) {
console.error(`Failed to initialize or get tools from MCP server ${server.name} (ID: ${server.id}):`, mcpError);
}
}
} catch (dbError) {
console.error('Failed to fetch enabled MCP servers:', dbError);
}
const activeToolsList = selectedChatModel === 'chat-model-reasoning'
? []
: Object.keys(combinedTools);
const result = streamText({
model: myProvider.languageModel(selectedChatModel),
system: systemPrompt({ selectedChatModel }),
messages,
maxSteps: 5,
tools: combinedTools,
experimental_activeTools: activeToolsList,
experimental_transform: smoothStream({ chunking: 'word' }),
experimental_generateMessageId: generateUUID,
onFinish: async ({ response }) => {
if (session.user?.id) {
try {
const assistantId = getTrailingMessageId({
messages: response.messages.filter(
(message) => message.role === 'assistant',
),
});
if (!assistantId) {
throw new Error('No assistant message found!');
}
const [, assistantMessage] = appendResponseMessages({
messages: [userMessage],
responseMessages: response.messages,
});
await saveMessages({
messages: [
{
id: assistantId,
chatId: id,
role: assistantMessage.role,
parts: assistantMessage.parts,
attachments:
assistantMessage.experimental_attachments ?? [],
createdAt: new Date(),
},
],
});
} catch (_) {
console.error('Failed to save chat messages after stream completion');
}
}
console.log(`Closing ${mcpClientsToClose.length} MCP clients in onFinish...`);
for (const client of mcpClientsToClose) {
try {
await client.close();
} catch (closeError: unknown) {
console.error('Error closing MCP client in onFinish:', closeError);
}
}
mcpClientsToClose = [];
},
experimental_telemetry: {
isEnabled: isProductionEnvironment,
functionId: 'stream-text',
},
});
result.consumeStream();
result.mergeIntoDataStream(dataStream, { sendReasoning: true });
} catch(streamError) {
console.error('Error during streamText execution or MCP setup:', streamError);
throw streamError;
} finally {
console.log('Stream execute try/catch finished.');
}
},
onError: (error) => {
console.error('Data stream error:', error);
return 'Oops, an error occured!';
},
});
} catch (error) {
console.error('Error in POST /api/chat route (initial setup):', error);
for (const client of mcpClientsToClose) {
client.close().catch((closeError: unknown) => console.error('Error closing MCP client during outer catch:', closeError));
}
return new Response('An error occurred while processing your request!', {
status: 500,
});
}
}
export async function DELETE(request: Request) {
const { searchParams } = new URL(request.url);
const id = searchParams.get('id');
if (!id) {
return new Response('Not Found', { status: 404 });
}
const session = await auth();
if (!session || !session.user) {
return new Response('Unauthorized', { status: 401 });
}
try {
const chat = await getChatById({ id });
if (chat.userId !== session.user.id) {
return new Response('Unauthorized', { status: 401 });
}
await deleteChatById({ id });
return new Response('Chat deleted', { status: 200 });
} catch (error) {
console.error('Error deleting chat:', error);
return new Response('An error occurred while processing your request!', {
status: 500,
});
}
}