feat(mcp): add Model Context Protocol integration
Add MCP integration including: - New MCP settings tab with server configuration - Tool invocation UI components - API endpoints for MCP management - Integration with chat system for tool execution - Example configurations
This commit is contained in:
@@ -7,6 +7,16 @@ import { WORK_DIR } from '~/utils/constants';
|
||||
import WithTooltip from '~/components/ui/Tooltip';
|
||||
import type { Message } from 'ai';
|
||||
import type { ProviderInfo } from '~/types/model';
|
||||
import type {
|
||||
TextUIPart,
|
||||
ReasoningUIPart,
|
||||
ToolInvocationUIPart,
|
||||
SourceUIPart,
|
||||
FileUIPart,
|
||||
StepStartUIPart,
|
||||
} from '@ai-sdk/ui-utils';
|
||||
import { ToolInvocations } from './ToolInvocations';
|
||||
import type { ToolCallAnnotation } from '~/types/context';
|
||||
|
||||
interface AssistantMessageProps {
|
||||
content: string;
|
||||
@@ -19,6 +29,10 @@ interface AssistantMessageProps {
|
||||
setChatMode?: (mode: 'discuss' | 'build') => void;
|
||||
model?: string;
|
||||
provider?: ProviderInfo;
|
||||
parts:
|
||||
| (TextUIPart | ReasoningUIPart | ToolInvocationUIPart | SourceUIPart | FileUIPart | StepStartUIPart)[]
|
||||
| undefined;
|
||||
addToolResult: ({ toolCallId, result }: { toolCallId: string; result: any }) => void;
|
||||
}
|
||||
|
||||
function openArtifactInWorkbench(filePath: string) {
|
||||
@@ -57,6 +71,8 @@ export const AssistantMessage = memo(
|
||||
setChatMode,
|
||||
model,
|
||||
provider,
|
||||
parts,
|
||||
addToolResult,
|
||||
}: AssistantMessageProps) => {
|
||||
const filteredAnnotations = (annotations?.filter(
|
||||
(annotation: JSONValue) =>
|
||||
@@ -81,6 +97,11 @@ export const AssistantMessage = memo(
|
||||
totalTokens: number;
|
||||
} = filteredAnnotations.find((annotation) => annotation.type === 'usage')?.value;
|
||||
|
||||
const toolInvocations = parts?.filter((part) => part.type === 'tool-invocation');
|
||||
const toolCallAnnotations = filteredAnnotations.filter(
|
||||
(annotation) => annotation.type === 'toolCall',
|
||||
) as ToolCallAnnotation[];
|
||||
|
||||
return (
|
||||
<div className="overflow-hidden w-full">
|
||||
<>
|
||||
@@ -155,6 +176,13 @@ export const AssistantMessage = memo(
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
{toolInvocations && toolInvocations.length > 0 && (
|
||||
<ToolInvocations
|
||||
toolInvocations={toolInvocations}
|
||||
toolCallAnnotations={toolCallAnnotations}
|
||||
addToolResult={addToolResult}
|
||||
/>
|
||||
)}
|
||||
<Markdown append={append} chatMode={chatMode} setChatMode={setChatMode} model={model} provider={provider} html>
|
||||
{content}
|
||||
</Markdown>
|
||||
|
||||
@@ -77,6 +77,7 @@ interface BaseChatProps {
|
||||
setDesignScheme?: (scheme: DesignScheme) => void;
|
||||
selectedElement?: ElementInfo | null;
|
||||
setSelectedElement?: (element: ElementInfo | null) => void;
|
||||
addToolResult?: ({ toolCallId, result }: { toolCallId: string; result: any }) => void;
|
||||
}
|
||||
|
||||
export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
|
||||
@@ -121,6 +122,9 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
|
||||
setDesignScheme,
|
||||
selectedElement,
|
||||
setSelectedElement,
|
||||
addToolResult = () => {
|
||||
throw new Error('addToolResult not implemented');
|
||||
},
|
||||
},
|
||||
ref,
|
||||
) => {
|
||||
@@ -369,6 +373,7 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
|
||||
setChatMode={setChatMode}
|
||||
provider={provider}
|
||||
model={model}
|
||||
addToolResult={addToolResult}
|
||||
/>
|
||||
) : null;
|
||||
}}
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
/*
|
||||
* @ts-nocheck
|
||||
* Preventing TS checks with files presented in the video for a better presentation.
|
||||
*/
|
||||
import { useStore } from '@nanostores/react';
|
||||
import type { Message } from 'ai';
|
||||
import { useChat } from 'ai/react';
|
||||
import { useChat } from '@ai-sdk/react';
|
||||
import { useAnimate } from 'framer-motion';
|
||||
import { memo, useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { cssTransition, toast, ToastContainer } from 'react-toastify';
|
||||
@@ -29,6 +25,8 @@ import { filesToArtifacts } from '~/utils/fileUtils';
|
||||
import { supabaseConnection } from '~/lib/stores/supabase';
|
||||
import { defaultDesignScheme, type DesignScheme } from '~/types/design-scheme';
|
||||
import type { ElementInfo } from '~/components/workbench/Inspector';
|
||||
import type { TextUIPart, FileUIPart, Attachment } from '@ai-sdk/ui-utils';
|
||||
import { useMCPStore } from '~/lib/stores/mcp';
|
||||
|
||||
const toastAnimation = cssTransition({
|
||||
enter: 'animated fadeInRight',
|
||||
@@ -148,6 +146,8 @@ export const ChatImpl = memo(
|
||||
const [apiKeys, setApiKeys] = useState<Record<string, string>>({});
|
||||
const [chatMode, setChatMode] = useState<'discuss' | 'build'>('build');
|
||||
const [selectedElement, setSelectedElement] = useState<ElementInfo | null>(null);
|
||||
const mcpSettings = useMCPStore((state) => state.settings);
|
||||
|
||||
const {
|
||||
messages,
|
||||
isLoading,
|
||||
@@ -161,6 +161,7 @@ export const ChatImpl = memo(
|
||||
error,
|
||||
data: chatData,
|
||||
setData,
|
||||
addToolResult,
|
||||
} = useChat({
|
||||
api: '/api/chat',
|
||||
body: {
|
||||
@@ -178,6 +179,7 @@ export const ChatImpl = memo(
|
||||
anonKey: supabaseConn?.credentials?.anonKey,
|
||||
},
|
||||
},
|
||||
maxLLMSteps: mcpSettings.maxLLMSteps,
|
||||
},
|
||||
sendExtraMessageFields: true,
|
||||
onError: (e) => {
|
||||
@@ -222,12 +224,7 @@ export const ChatImpl = memo(
|
||||
runAnimation();
|
||||
append({
|
||||
role: 'user',
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
text: `[Model: ${model}]\n\n[Provider: ${provider.name}]\n\n${prompt}`,
|
||||
},
|
||||
] as any, // Type assertion to bypass compiler check
|
||||
content: `[Model: ${model}]\n\n[Provider: ${provider.name}]\n\n${prompt}`,
|
||||
});
|
||||
}
|
||||
}, [model, provider, searchParams]);
|
||||
@@ -300,6 +297,59 @@ export const ChatImpl = memo(
|
||||
setChatStarted(true);
|
||||
};
|
||||
|
||||
// Helper function to create message parts array from text and images
|
||||
const createMessageParts = (text: string, images: string[] = []): Array<TextUIPart | FileUIPart> => {
|
||||
// Create an array of properly typed message parts
|
||||
const parts: Array<TextUIPart | FileUIPart> = [
|
||||
{
|
||||
type: 'text',
|
||||
text,
|
||||
},
|
||||
];
|
||||
|
||||
// Add image parts if any
|
||||
images.forEach((imageData) => {
|
||||
// Extract correct MIME type from the data URL
|
||||
const mimeType = imageData.split(';')[0].split(':')[1] || 'image/jpeg';
|
||||
|
||||
// Create file part according to AI SDK format
|
||||
parts.push({
|
||||
type: 'file',
|
||||
mimeType,
|
||||
data: imageData.replace(/^data:image\/[^;]+;base64,/, ''),
|
||||
});
|
||||
});
|
||||
|
||||
return parts;
|
||||
};
|
||||
|
||||
// Helper function to convert File[] to Attachment[] for AI SDK
|
||||
const filesToAttachments = async (files: File[]): Promise<Attachment[] | undefined> => {
|
||||
if (files.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const attachments = await Promise.all(
|
||||
files.map(
|
||||
(file) =>
|
||||
new Promise<Attachment>((resolve) => {
|
||||
const reader = new FileReader();
|
||||
|
||||
reader.onloadend = () => {
|
||||
resolve({
|
||||
name: file.name,
|
||||
contentType: file.type,
|
||||
url: reader.result as string,
|
||||
});
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return attachments;
|
||||
};
|
||||
|
||||
const sendMessage = async (_event: React.UIEvent, messageInput?: string) => {
|
||||
const messageContent = messageInput || input;
|
||||
|
||||
@@ -346,20 +396,14 @@ export const ChatImpl = memo(
|
||||
|
||||
if (temResp) {
|
||||
const { assistantMessage, userMessage } = temResp;
|
||||
const userMessageText = `[Model: ${model}]\n\n[Provider: ${provider.name}]\n\n${finalMessageContent}`;
|
||||
|
||||
setMessages([
|
||||
{
|
||||
id: `1-${new Date().getTime()}`,
|
||||
role: 'user',
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
text: `[Model: ${model}]\n\n[Provider: ${provider.name}]\n\n${finalMessageContent}`,
|
||||
},
|
||||
...imageDataList.map((imageData) => ({
|
||||
type: 'image',
|
||||
image: imageData,
|
||||
})),
|
||||
] as any,
|
||||
content: userMessageText,
|
||||
parts: createMessageParts(userMessageText, imageDataList),
|
||||
},
|
||||
{
|
||||
id: `2-${new Date().getTime()}`,
|
||||
@@ -373,7 +417,13 @@ export const ChatImpl = memo(
|
||||
annotations: ['hidden'],
|
||||
},
|
||||
]);
|
||||
reload();
|
||||
|
||||
const reloadOptions =
|
||||
uploadedFiles.length > 0
|
||||
? { experimental_attachments: await filesToAttachments(uploadedFiles) }
|
||||
: undefined;
|
||||
|
||||
reload(reloadOptions);
|
||||
setInput('');
|
||||
Cookies.remove(PROMPT_COOKIE_KEY);
|
||||
|
||||
@@ -391,23 +441,19 @@ export const ChatImpl = memo(
|
||||
}
|
||||
|
||||
// If autoSelectTemplate is disabled or template selection failed, proceed with normal message
|
||||
const userMessageText = `[Model: ${model}]\n\n[Provider: ${provider.name}]\n\n${finalMessageContent}`;
|
||||
const attachments = uploadedFiles.length > 0 ? await filesToAttachments(uploadedFiles) : undefined;
|
||||
|
||||
setMessages([
|
||||
{
|
||||
id: `${new Date().getTime()}`,
|
||||
role: 'user',
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
text: `[Model: ${model}]\n\n[Provider: ${provider.name}]\n\n${finalMessageContent}`,
|
||||
},
|
||||
...imageDataList.map((imageData) => ({
|
||||
type: 'image',
|
||||
image: imageData,
|
||||
})),
|
||||
] as any,
|
||||
content: userMessageText,
|
||||
parts: createMessageParts(userMessageText, imageDataList),
|
||||
experimental_attachments: attachments,
|
||||
},
|
||||
]);
|
||||
reload();
|
||||
reload(attachments ? { experimental_attachments: attachments } : undefined);
|
||||
setFakeLoading(false);
|
||||
setInput('');
|
||||
Cookies.remove(PROMPT_COOKIE_KEY);
|
||||
@@ -432,35 +478,35 @@ export const ChatImpl = memo(
|
||||
|
||||
if (modifiedFiles !== undefined) {
|
||||
const userUpdateArtifact = filesToArtifacts(modifiedFiles, `${Date.now()}`);
|
||||
append({
|
||||
role: 'user',
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
text: `[Model: ${model}]\n\n[Provider: ${provider.name}]\n\n${userUpdateArtifact}${finalMessageContent}`,
|
||||
},
|
||||
...imageDataList.map((imageData) => ({
|
||||
type: 'image',
|
||||
image: imageData,
|
||||
})),
|
||||
] as any,
|
||||
});
|
||||
const messageText = `[Model: ${model}]\n\n[Provider: ${provider.name}]\n\n${userUpdateArtifact}${finalMessageContent}`;
|
||||
|
||||
const attachmentOptions =
|
||||
uploadedFiles.length > 0 ? { experimental_attachments: await filesToAttachments(uploadedFiles) } : undefined;
|
||||
|
||||
append(
|
||||
{
|
||||
role: 'user',
|
||||
content: messageText,
|
||||
parts: createMessageParts(messageText, imageDataList),
|
||||
},
|
||||
attachmentOptions,
|
||||
);
|
||||
|
||||
workbenchStore.resetAllFileModifications();
|
||||
} else {
|
||||
append({
|
||||
role: 'user',
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
text: `[Model: ${model}]\n\n[Provider: ${provider.name}]\n\n${finalMessageContent}`,
|
||||
},
|
||||
...imageDataList.map((imageData) => ({
|
||||
type: 'image',
|
||||
image: imageData,
|
||||
})),
|
||||
] as any,
|
||||
});
|
||||
const messageText = `[Model: ${model}]\n\n[Provider: ${provider.name}]\n\n${finalMessageContent}`;
|
||||
|
||||
const attachmentOptions =
|
||||
uploadedFiles.length > 0 ? { experimental_attachments: await filesToAttachments(uploadedFiles) } : undefined;
|
||||
|
||||
append(
|
||||
{
|
||||
role: 'user',
|
||||
content: messageText,
|
||||
parts: createMessageParts(messageText, imageDataList),
|
||||
},
|
||||
attachmentOptions,
|
||||
);
|
||||
}
|
||||
|
||||
setInput('');
|
||||
@@ -579,6 +625,7 @@ export const ChatImpl = memo(
|
||||
setDesignScheme={setDesignScheme}
|
||||
selectedElement={selectedElement}
|
||||
setSelectedElement={setSelectedElement}
|
||||
addToolResult={addToolResult}
|
||||
/>
|
||||
);
|
||||
},
|
||||
|
||||
@@ -18,6 +18,7 @@ import type { ProviderInfo } from '~/types/model';
|
||||
import { ColorSchemeDialog } from '~/components/ui/ColorSchemeDialog';
|
||||
import type { DesignScheme } from '~/types/design-scheme';
|
||||
import type { ElementInfo } from '~/components/workbench/Inspector';
|
||||
import { McpTools } from './MCPTools';
|
||||
|
||||
interface ChatBoxProps {
|
||||
isModelSettingsCollapsed: boolean;
|
||||
@@ -260,6 +261,7 @@ export const ChatBox: React.FC<ChatBoxProps> = (props) => {
|
||||
<div className="flex justify-between items-center text-sm p-4 pt-2">
|
||||
<div className="flex gap-1 items-center">
|
||||
<ColorSchemeDialog designScheme={props.designScheme} setDesignScheme={props.setDesignScheme} />
|
||||
<McpTools />
|
||||
<IconButton title="Upload file" className="transition-all" onClick={() => props.handleFileUpload()}>
|
||||
<div className="i-ph:paperclip text-xl"></div>
|
||||
</IconButton>
|
||||
|
||||
129
app/components/chat/MCPTools.tsx
Normal file
129
app/components/chat/MCPTools.tsx
Normal file
@@ -0,0 +1,129 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
import { Dialog, DialogRoot, DialogClose, DialogTitle, DialogButton } from '~/components/ui/Dialog';
|
||||
import { IconButton } from '~/components/ui/IconButton';
|
||||
import { useMCPStore } from '~/lib/stores/mcp';
|
||||
import McpServerList from '~/components/@settings/tabs/mcp/McpServerList';
|
||||
|
||||
export function McpTools() {
|
||||
const isInitialized = useMCPStore((state) => state.isInitialized);
|
||||
const serverTools = useMCPStore((state) => state.serverTools);
|
||||
const initialize = useMCPStore((state) => state.initialize);
|
||||
const checkServersAvailabilities = useMCPStore((state) => state.checkServersAvailabilities);
|
||||
|
||||
const [isDialogOpen, setIsDialogOpen] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isCheckingServers, setIsCheckingServers] = useState(false);
|
||||
const [expandedServer, setExpandedServer] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isInitialized) {
|
||||
initialize();
|
||||
}
|
||||
}, [isInitialized]);
|
||||
|
||||
const checkServerAvailability = async () => {
|
||||
setIsCheckingServers(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
await checkServersAvailabilities();
|
||||
} catch (e) {
|
||||
setError(`Failed to check server availability: ${e instanceof Error ? e.message : String(e)}`);
|
||||
} finally {
|
||||
setIsCheckingServers(false);
|
||||
}
|
||||
};
|
||||
|
||||
const toggleServerExpanded = (serverName: string) => {
|
||||
setExpandedServer(expandedServer === serverName ? null : serverName);
|
||||
};
|
||||
|
||||
const handleDialogOpen = (open: boolean) => {
|
||||
setIsDialogOpen(open);
|
||||
};
|
||||
|
||||
const serverEntries = useMemo(() => Object.entries(serverTools), [serverTools]);
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
<div className="flex">
|
||||
<IconButton
|
||||
onClick={() => setIsDialogOpen(!isDialogOpen)}
|
||||
title="MCP Tools Available"
|
||||
disabled={!isInitialized}
|
||||
className="transition-all disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
{!isInitialized ? (
|
||||
<div className="i-svg-spinners:90-ring-with-bg text-bolt-elements-loader-progress text-xl animate-spin"></div>
|
||||
) : (
|
||||
<div className="i-bolt:mcp text-xl"></div>
|
||||
)}
|
||||
</IconButton>
|
||||
</div>
|
||||
|
||||
<DialogRoot open={isDialogOpen} onOpenChange={handleDialogOpen}>
|
||||
{isDialogOpen && (
|
||||
<Dialog className="max-w-4xl w-full p-6">
|
||||
<div className="space-y-4 max-h-[80vh] overflow-y-auto pr-2">
|
||||
<DialogTitle>
|
||||
<div className="i-bolt:mcp text-xl"></div>
|
||||
MCP tools
|
||||
</DialogTitle>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<div className="flex justify-end items-center mb-2">
|
||||
<button
|
||||
onClick={checkServerAvailability}
|
||||
disabled={isCheckingServers || serverEntries.length === 0}
|
||||
className={classNames(
|
||||
'px-3 py-1.5 rounded-lg text-sm',
|
||||
'bg-bolt-elements-background-depth-3 hover:bg-bolt-elements-background-depth-4',
|
||||
'text-bolt-elements-textPrimary',
|
||||
'transition-all duration-200',
|
||||
'flex items-center gap-2',
|
||||
'disabled:opacity-50 disabled:cursor-not-allowed',
|
||||
)}
|
||||
>
|
||||
{isCheckingServers ? (
|
||||
<div className="i-svg-spinners:90-ring-with-bg w-3 h-3 text-bolt-elements-loader-progress animate-spin" />
|
||||
) : (
|
||||
<div className="i-ph:arrow-counter-clockwise w-3 h-3" />
|
||||
)}
|
||||
Check availability
|
||||
</button>
|
||||
</div>
|
||||
{serverEntries.length > 0 ? (
|
||||
<McpServerList
|
||||
checkingServers={isCheckingServers}
|
||||
expandedServer={expandedServer}
|
||||
serverEntries={serverEntries}
|
||||
onlyShowAvailableServers={true}
|
||||
toggleServerExpanded={toggleServerExpanded}
|
||||
/>
|
||||
) : (
|
||||
<div className="py-4 text-center text-bolt-elements-textSecondary">
|
||||
<p>No MCP servers configured</p>
|
||||
<p className="text-xs mt-1">Configure servers in Settings → MCP Servers</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>{error && <p className="mt-2 text-sm text-bolt-elements-icon-error">{error}</p>}</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-2 mt-6">
|
||||
<div className="flex gap-2">
|
||||
<DialogClose asChild>
|
||||
<DialogButton type="secondary">Close</DialogButton>
|
||||
</DialogClose>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Dialog>
|
||||
)}
|
||||
</DialogRoot>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -21,6 +21,7 @@ interface MessagesProps {
|
||||
setChatMode?: (mode: 'discuss' | 'build') => void;
|
||||
model?: string;
|
||||
provider?: ProviderInfo;
|
||||
addToolResult: ({ toolCallId, result }: { toolCallId: string; result: any }) => void;
|
||||
}
|
||||
|
||||
export const Messages = forwardRef<HTMLDivElement, MessagesProps>(
|
||||
@@ -52,7 +53,7 @@ export const Messages = forwardRef<HTMLDivElement, MessagesProps>(
|
||||
<div id={id} className={props.className} ref={ref}>
|
||||
{messages.length > 0
|
||||
? messages.map((message, index) => {
|
||||
const { role, content, id: messageId, annotations } = message;
|
||||
const { role, content, id: messageId, annotations, parts } = message;
|
||||
const isUserMessage = role === 'user';
|
||||
const isFirst = index === 0;
|
||||
const isHidden = annotations?.includes('hidden');
|
||||
@@ -83,6 +84,8 @@ export const Messages = forwardRef<HTMLDivElement, MessagesProps>(
|
||||
setChatMode={props.setChatMode}
|
||||
model={props.model}
|
||||
provider={props.provider}
|
||||
parts={parts}
|
||||
addToolResult={props.addToolResult}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
367
app/components/chat/ToolInvocations.tsx
Normal file
367
app/components/chat/ToolInvocations.tsx
Normal file
@@ -0,0 +1,367 @@
|
||||
import type { ToolInvocationUIPart } from '@ai-sdk/ui-utils';
|
||||
import { AnimatePresence, motion } from 'framer-motion';
|
||||
import { memo, useMemo, useState } from 'react';
|
||||
import { createHighlighter, type BundledLanguage, type BundledTheme, type HighlighterGeneric } from 'shiki';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
import {
|
||||
TOOL_EXECUTION_APPROVAL,
|
||||
TOOL_EXECUTION_DENIED,
|
||||
TOOL_EXECUTION_ERROR,
|
||||
TOOL_NO_EXECUTE_FUNCTION,
|
||||
} from '~/utils/constants';
|
||||
import { cubicEasingFn } from '~/utils/easings';
|
||||
import { logger } from '~/utils/logger';
|
||||
import { themeStore, type Theme } from '~/lib/stores/theme';
|
||||
import { useStore } from '@nanostores/react';
|
||||
import type { ToolCallAnnotation } from '~/types/context';
|
||||
|
||||
const highlighterOptions = {
|
||||
langs: ['json'],
|
||||
themes: ['light-plus', 'dark-plus'],
|
||||
};
|
||||
|
||||
const jsonHighlighter: HighlighterGeneric<BundledLanguage, BundledTheme> =
|
||||
import.meta.hot?.data.jsonHighlighter ?? (await createHighlighter(highlighterOptions));
|
||||
|
||||
if (import.meta.hot) {
|
||||
import.meta.hot.data.jsonHighlighter = jsonHighlighter;
|
||||
}
|
||||
|
||||
interface JsonCodeBlockProps {
|
||||
className?: string;
|
||||
code: string;
|
||||
theme: Theme;
|
||||
}
|
||||
|
||||
function JsonCodeBlock({ className, code, theme }: JsonCodeBlockProps) {
|
||||
let formattedCode = code;
|
||||
|
||||
try {
|
||||
if (typeof formattedCode === 'object') {
|
||||
formattedCode = JSON.stringify(formattedCode, null, 2);
|
||||
} else if (typeof formattedCode === 'string') {
|
||||
// Attempt to parse and re-stringify for formatting
|
||||
try {
|
||||
const parsed = JSON.parse(formattedCode);
|
||||
formattedCode = JSON.stringify(parsed, null, 2);
|
||||
} catch {
|
||||
// Leave as is if not JSON
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
// If parsing fails, keep original code
|
||||
logger.error('Failed to parse JSON', { error: e });
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={classNames('text-xs rounded-md overflow-hidden mcp-tool-invocation-code', className)}
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: jsonHighlighter.codeToHtml(formattedCode, {
|
||||
lang: 'json',
|
||||
theme: theme === 'dark' ? 'dark-plus' : 'light-plus',
|
||||
}),
|
||||
}}
|
||||
style={{
|
||||
padding: '0',
|
||||
margin: '0',
|
||||
}}
|
||||
></div>
|
||||
);
|
||||
}
|
||||
|
||||
interface ToolInvocationsProps {
|
||||
toolInvocations: ToolInvocationUIPart[];
|
||||
toolCallAnnotations: ToolCallAnnotation[];
|
||||
addToolResult: ({ toolCallId, result }: { toolCallId: string; result: any }) => void;
|
||||
}
|
||||
|
||||
export const ToolInvocations = memo(({ toolInvocations, toolCallAnnotations, addToolResult }: ToolInvocationsProps) => {
|
||||
const theme = useStore(themeStore);
|
||||
const [showDetails, setShowDetails] = useState(false);
|
||||
|
||||
const toggleDetails = () => {
|
||||
setShowDetails((prev) => !prev);
|
||||
};
|
||||
|
||||
const toolCalls = useMemo(
|
||||
() => toolInvocations.filter((inv) => inv.toolInvocation.state === 'call'),
|
||||
[toolInvocations],
|
||||
);
|
||||
|
||||
const toolResults = useMemo(
|
||||
() => toolInvocations.filter((inv) => inv.toolInvocation.state === 'result'),
|
||||
[toolInvocations],
|
||||
);
|
||||
|
||||
const hasToolCalls = toolCalls.length > 0;
|
||||
const hasToolResults = toolResults.length > 0;
|
||||
|
||||
if (!hasToolCalls && !hasToolResults) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="tool-invocation border border-bolt-elements-borderColor flex flex-col overflow-hidden rounded-lg w-full transition-border duration-150 mt-4 mb-4">
|
||||
<div className="flex">
|
||||
<button
|
||||
className="flex items-stretch bg-bolt-elements-artifacts-background hover:bg-bolt-elements-artifacts-backgroundHover w-full overflow-hidden"
|
||||
onClick={toggleDetails}
|
||||
aria-label={showDetails ? 'Collapse details' : 'Expand details'}
|
||||
>
|
||||
<div className="p-2">
|
||||
<div className="i-ph:wrench-fill text-xl text-bolt-elements-textSecondary hover:text-bolt-elements-textPrimary transition-colors"></div>
|
||||
</div>
|
||||
<div className="bg-bolt-elements-artifacts-borderColor w-[1px]" />
|
||||
<div className="px-5 p-2 w-full text-left">
|
||||
<div className="w-full text-bolt-elements-textPrimary font-medium leading-5 text-sm">
|
||||
MCP Tool Invocations{' '}
|
||||
{hasToolResults && (
|
||||
<span className="w-full w-full text-bolt-elements-textSecondary text-xs mt-0.5">
|
||||
({toolResults.length} tool{hasToolResults ? 's' : ''} used)
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
<div className="bg-bolt-elements-artifacts-borderColor w-[1px]" />
|
||||
<AnimatePresence>
|
||||
{hasToolResults && (
|
||||
<motion.button
|
||||
initial={{ width: 0 }}
|
||||
animate={{ width: 'auto' }}
|
||||
exit={{ width: 0 }}
|
||||
transition={{ duration: 0.15, ease: cubicEasingFn }}
|
||||
className="bg-bolt-elements-artifacts-background hover:bg-bolt-elements-artifacts-backgroundHover"
|
||||
onClick={toggleDetails}
|
||||
>
|
||||
<div className="p-2">
|
||||
<div
|
||||
className={`${showDetails ? 'i-ph:caret-up-bold' : 'i-ph:caret-down-bold'} text-xl text-bolt-elements-textSecondary hover:text-bolt-elements-textPrimary transition-colors`}
|
||||
></div>
|
||||
</div>
|
||||
</motion.button>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
<AnimatePresence>
|
||||
{hasToolCalls && (
|
||||
<motion.div
|
||||
className="details"
|
||||
initial={{ height: 0 }}
|
||||
animate={{ height: 'auto' }}
|
||||
exit={{ height: '0px' }}
|
||||
transition={{ duration: 0.15 }}
|
||||
>
|
||||
<div className="bg-bolt-elements-artifacts-borderColor h-[1px]" />
|
||||
|
||||
<div className="p-5 text-left bg-bolt-elements-actions-background">
|
||||
<ToolCallsList
|
||||
toolInvocations={toolCalls}
|
||||
toolCallAnnotations={toolCallAnnotations}
|
||||
addToolResult={addToolResult}
|
||||
theme={theme}
|
||||
/>
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
{hasToolResults && showDetails && (
|
||||
<motion.div
|
||||
className="details"
|
||||
initial={{ height: 0 }}
|
||||
animate={{ height: 'auto' }}
|
||||
exit={{ height: '0px' }}
|
||||
transition={{ duration: 0.15 }}
|
||||
>
|
||||
<div className="bg-bolt-elements-artifacts-borderColor h-[1px]" />
|
||||
|
||||
<div className="p-5 text-left bg-bolt-elements-actions-background">
|
||||
<ToolResultsList toolInvocations={toolResults} toolCallAnnotations={toolCallAnnotations} theme={theme} />
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
const toolVariants = {
|
||||
hidden: { opacity: 0, y: 20 },
|
||||
visible: { opacity: 1, y: 0 },
|
||||
};
|
||||
|
||||
interface ToolResultsListProps {
|
||||
toolInvocations: ToolInvocationUIPart[];
|
||||
toolCallAnnotations: ToolCallAnnotation[];
|
||||
theme: Theme;
|
||||
}
|
||||
|
||||
const ToolResultsList = memo(({ toolInvocations, toolCallAnnotations, theme }: ToolResultsListProps) => {
|
||||
return (
|
||||
<motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} transition={{ duration: 0.15 }}>
|
||||
<ul className="list-none space-y-4">
|
||||
{toolInvocations.map((tool, index) => {
|
||||
const toolCallState = tool.toolInvocation.state;
|
||||
|
||||
if (toolCallState !== 'result') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const { toolName, toolCallId } = tool.toolInvocation;
|
||||
|
||||
const annotation = toolCallAnnotations.find((annotation) => {
|
||||
return annotation.toolCallId === toolCallId;
|
||||
});
|
||||
|
||||
const isErrorResult = [TOOL_NO_EXECUTE_FUNCTION, TOOL_EXECUTION_DENIED, TOOL_EXECUTION_ERROR].includes(
|
||||
tool.toolInvocation.result,
|
||||
);
|
||||
|
||||
return (
|
||||
<motion.li
|
||||
key={index}
|
||||
variants={toolVariants}
|
||||
initial="hidden"
|
||||
animate="visible"
|
||||
transition={{
|
||||
duration: 0.2,
|
||||
ease: cubicEasingFn,
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center gap-1.5 text-xs mb-1">
|
||||
{isErrorResult ? (
|
||||
<div className="text-lg text-bolt-elements-icon-error">
|
||||
<div className="i-ph:x"></div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-lg text-bolt-elements-icon-success">
|
||||
<div className="i-ph:check"></div>
|
||||
</div>
|
||||
)}
|
||||
<div className="text-bolt-elements-textSecondary text-xs">Server:</div>
|
||||
<div className="text-bolt-elements-textPrimary font-semibold">{annotation?.serverName}</div>
|
||||
</div>
|
||||
|
||||
<div className="ml-6 mb-2">
|
||||
<div className="text-bolt-elements-textSecondary text-xs mb-1">
|
||||
Tool: <span className="text-bolt-elements-textPrimary font-semibold">{toolName}</span>
|
||||
</div>
|
||||
<div className="text-bolt-elements-textSecondary text-xs mb-1">
|
||||
Description:{' '}
|
||||
<span className="text-bolt-elements-textPrimary font-semibold">{annotation?.toolDescription}</span>
|
||||
</div>
|
||||
<div className="text-bolt-elements-textSecondary text-xs mb-1">Parameters:</div>
|
||||
<div className="bg-[#FAFAFA] dark:bg-[#0A0A0A] p-3 rounded-md">
|
||||
<JsonCodeBlock className="mb-0" code={JSON.stringify(tool.toolInvocation.args)} theme={theme} />
|
||||
</div>
|
||||
<div className="text-bolt-elements-textSecondary text-xs mt-3 mb-1">Result:</div>
|
||||
<div className="bg-[#FAFAFA] dark:bg-[#0A0A0A] p-3 rounded-md">
|
||||
<JsonCodeBlock className="mb-0" code={JSON.stringify(tool.toolInvocation.result)} theme={theme} />
|
||||
</div>
|
||||
</div>
|
||||
</motion.li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</motion.div>
|
||||
);
|
||||
});
|
||||
|
||||
interface ToolCallsListProps {
|
||||
toolInvocations: ToolInvocationUIPart[];
|
||||
toolCallAnnotations: ToolCallAnnotation[];
|
||||
addToolResult: ({ toolCallId, result }: { toolCallId: string; result: any }) => void;
|
||||
theme: Theme;
|
||||
}
|
||||
|
||||
const ToolCallsList = memo(({ toolInvocations, toolCallAnnotations, addToolResult, theme }: ToolCallsListProps) => {
|
||||
return (
|
||||
<motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} transition={{ duration: 0.15 }}>
|
||||
<ul className="list-none space-y-4">
|
||||
{toolInvocations.map((tool, index) => {
|
||||
const toolCallState = tool.toolInvocation.state;
|
||||
|
||||
if (toolCallState !== 'call') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const { toolName, toolCallId } = tool.toolInvocation;
|
||||
|
||||
const annotation = toolCallAnnotations.find((annotation) => {
|
||||
return annotation.toolCallId === toolCallId;
|
||||
});
|
||||
|
||||
return (
|
||||
<motion.li
|
||||
key={index}
|
||||
variants={toolVariants}
|
||||
initial="hidden"
|
||||
animate="visible"
|
||||
transition={{
|
||||
duration: 0.2,
|
||||
ease: cubicEasingFn,
|
||||
}}
|
||||
>
|
||||
<div className="ml-6 mb-2">
|
||||
<div key={toolCallId}>
|
||||
<div className="text-bolt-elements-textPrimary">Bolt wants to use a tool.</div>
|
||||
<div className="text-bolt-elements-textSecondary text-xs mb-1">
|
||||
Server:{' '}
|
||||
<span className="text-bolt-elements-textPrimary font-semibold">{annotation?.serverName}</span>
|
||||
</div>
|
||||
<div className="text-bolt-elements-textSecondary text-xs mb-1">
|
||||
Tool: <span className="text-bolt-elements-textPrimary font-semibold">{toolName}</span>
|
||||
</div>
|
||||
<div className="text-bolt-elements-textSecondary text-xs mb-1">
|
||||
Description:{' '}
|
||||
<span className="text-bolt-elements-textPrimary font-semibold">{annotation?.toolDescription}</span>
|
||||
</div>
|
||||
<div className="text-bolt-elements-textSecondary text-xs mb-1">Parameters:</div>
|
||||
<div className="bg-[#FAFAFA] dark:bg-[#0A0A0A] p-3 rounded-md">
|
||||
<JsonCodeBlock className="mb-0" code={JSON.stringify(tool.toolInvocation.args)} theme={theme} />
|
||||
</div>{' '}
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<button
|
||||
className={classNames(
|
||||
'inline-flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-lg transition-colors',
|
||||
'bg-purple-500 hover:bg-purple-600',
|
||||
'text-white',
|
||||
'disabled:opacity-50 disabled:cursor-not-allowed',
|
||||
)}
|
||||
onClick={() =>
|
||||
addToolResult({
|
||||
toolCallId,
|
||||
result: TOOL_EXECUTION_APPROVAL.APPROVE,
|
||||
})
|
||||
}
|
||||
>
|
||||
Approve
|
||||
</button>
|
||||
<button
|
||||
className={classNames(
|
||||
'px-3 py-1.5 rounded-lg text-sm',
|
||||
'bg-bolt-elements-background-depth-3 hover:bg-bolt-elements-background-depth-4',
|
||||
'text-bolt-elements-textPrimary',
|
||||
'transition-all duration-200',
|
||||
'flex items-center gap-2',
|
||||
)}
|
||||
onClick={() =>
|
||||
addToolResult({
|
||||
toolCallId,
|
||||
result: TOOL_EXECUTION_APPROVAL.REJECT,
|
||||
})
|
||||
}
|
||||
>
|
||||
Reject
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</motion.li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</motion.div>
|
||||
);
|
||||
});
|
||||
Reference in New Issue
Block a user