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:
Roamin
2025-07-10 17:54:15 +00:00
parent 591c84572d
commit 5de162eec8
26 changed files with 2040 additions and 98 deletions

View File

@@ -38,6 +38,7 @@ import CloudProvidersTab from '~/components/@settings/tabs/providers/cloud/Cloud
import ServiceStatusTab from '~/components/@settings/tabs/providers/status/ServiceStatusTab';
import LocalProvidersTab from '~/components/@settings/tabs/providers/local/LocalProvidersTab';
import TaskManagerTab from '~/components/@settings/tabs/task-manager/TaskManagerTab';
import McpTab from '~/components/@settings/tabs/mcp/McpTab';
interface ControlPanelProps {
open: boolean;
@@ -81,6 +82,7 @@ const TAB_DESCRIPTIONS: Record<TabType, string> = {
update: 'Check for updates and release notes',
'task-manager': 'Monitor system resources and processes',
'tab-management': 'Configure visible tabs and their order',
mcp: 'Configure MCP (Model Context Protocol) servers',
};
// Beta status for experimental features
@@ -335,6 +337,8 @@ export const ControlPanel = ({ open, onClose }: ControlPanelProps) => {
return <TaskManagerTab />;
case 'service-status':
return <ServiceStatusTab />;
case 'mcp':
return <McpTab />;
default:
return null;
}

View File

@@ -15,6 +15,7 @@ export const TAB_ICONS: Record<TabType, string> = {
update: 'i-ph:arrow-clockwise-fill',
'task-manager': 'i-ph:chart-line-fill',
'tab-management': 'i-ph:squares-four-fill',
mcp: 'i-ph:hard-drives-bold',
};
export const TAB_LABELS: Record<TabType, string> = {
@@ -32,6 +33,7 @@ export const TAB_LABELS: Record<TabType, string> = {
update: 'Updates',
'task-manager': 'Task Manager',
'tab-management': 'Tab Management',
mcp: 'MCP Servers',
};
export const TAB_DESCRIPTIONS: Record<TabType, string> = {
@@ -49,6 +51,7 @@ export const TAB_DESCRIPTIONS: Record<TabType, string> = {
update: 'Check for updates and release notes',
'task-manager': 'Monitor system resources and processes',
'tab-management': 'Configure visible tabs and their order',
mcp: 'Configure MCP (Model Context Protocol) servers',
};
export const DEFAULT_TAB_CONFIG = [
@@ -58,18 +61,19 @@ export const DEFAULT_TAB_CONFIG = [
{ id: 'cloud-providers', visible: true, window: 'user' as const, order: 2 },
{ id: 'local-providers', visible: true, window: 'user' as const, order: 3 },
{ id: 'connection', visible: true, window: 'user' as const, order: 4 },
{ id: 'notifications', visible: true, window: 'user' as const, order: 5 },
{ id: 'event-logs', visible: true, window: 'user' as const, order: 6 },
{ id: 'connection', visible: true, window: 'user' as const, order: 5 },
{ id: 'notifications', visible: true, window: 'user' as const, order: 6 },
{ id: 'mcp', visible: true, window: 'user' as const, order: 7 },
// User Window Tabs (In dropdown, initially hidden)
{ id: 'profile', visible: false, window: 'user' as const, order: 7 },
{ id: 'settings', visible: false, window: 'user' as const, order: 8 },
{ id: 'task-manager', visible: false, window: 'user' as const, order: 9 },
{ id: 'service-status', visible: false, window: 'user' as const, order: 10 },
{ id: 'profile', visible: false, window: 'user' as const, order: 8 },
{ id: 'settings', visible: false, window: 'user' as const, order: 9 },
{ id: 'task-manager', visible: false, window: 'user' as const, order: 10 },
{ id: 'service-status', visible: false, window: 'user' as const, order: 11 },
// User Window Tabs (Hidden, controlled by TaskManagerTab)
{ id: 'debug', visible: false, window: 'user' as const, order: 11 },
{ id: 'update', visible: false, window: 'user' as const, order: 12 },
{ id: 'debug', visible: false, window: 'user' as const, order: 12 },
{ id: 'update', visible: false, window: 'user' as const, order: 13 },
// Developer Window Tabs (All visible by default)
{ id: 'features', visible: true, window: 'developer' as const, order: 0 },

View File

@@ -16,7 +16,8 @@ export type TabType =
| 'event-logs'
| 'update'
| 'task-manager'
| 'tab-management';
| 'tab-management'
| 'mcp';
export type WindowType = 'user' | 'developer';
@@ -81,6 +82,7 @@ export const TAB_LABELS: Record<TabType, string> = {
update: 'Updates',
'task-manager': 'Task Manager',
'tab-management': 'Tab Management',
mcp: 'MCP Servers',
};
export const categoryLabels: Record<SettingCategory, string> = {

View File

@@ -26,6 +26,7 @@ const TAB_ICONS: Record<TabType, string> = {
update: 'i-ph:arrow-clockwise-fill',
'task-manager': 'i-ph:chart-line-fill',
'tab-management': 'i-ph:squares-four-fill',
mcp: 'i-ph:hard-drives-bold',
};
// Define which tabs are default in user mode
@@ -37,6 +38,7 @@ const DEFAULT_USER_TABS: TabType[] = [
'connection',
'notifications',
'event-logs',
'mcp',
];
// Define which tabs can be added to user mode

View File

@@ -0,0 +1,99 @@
import type { MCPServer } from '~/lib/services/mcpService';
import McpStatusBadge from '~/components/@settings/tabs/mcp/McpStatusBadge';
import McpServerListItem from '~/components/@settings/tabs/mcp/McpServerListItem';
type McpServerListProps = {
serverEntries: [string, MCPServer][];
expandedServer: string | null;
checkingServers: boolean;
onlyShowAvailableServers?: boolean;
toggleServerExpanded: (serverName: string) => void;
};
export default function McpServerList({
serverEntries,
expandedServer,
checkingServers,
onlyShowAvailableServers = false,
toggleServerExpanded,
}: McpServerListProps) {
if (serverEntries.length === 0) {
return <p className="text-sm text-bolt-elements-textSecondary">No MCP servers configured</p>;
}
const filteredEntries = onlyShowAvailableServers
? serverEntries.filter(([, s]) => s.status === 'available')
: serverEntries;
return (
<div className="space-y-2">
{filteredEntries.map(([serverName, mcpServer]) => {
const isAvailable = mcpServer.status === 'available';
const isExpanded = expandedServer === serverName;
const serverTools = isAvailable ? Object.entries(mcpServer.tools) : [];
return (
<div key={serverName} className="flex flex-col p-2 rounded-md bg-bolt-elements-background-depth-1">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2 min-w-0 flex-1">
<div
onClick={() => toggleServerExpanded(serverName)}
className="flex items-center gap-1.5 text-bolt-elements-textPrimary"
aria-expanded={isExpanded}
>
<div
className={`i-ph:${isExpanded ? 'caret-down' : 'caret-right'} w-3 h-3 transition-transform duration-150`}
/>
<span className="font-medium truncate text-left">{serverName}</span>
</div>
<div className="flex-1 min-w-0 truncate">
{mcpServer.config.type === 'sse' || mcpServer.config.type === 'streamable-http' ? (
<span className="text-xs text-bolt-elements-textSecondary truncate">{mcpServer.config.url}</span>
) : (
<span className="text-xs text-bolt-elements-textSecondary truncate">
{mcpServer.config.command} {mcpServer.config.args?.join(' ')}
</span>
)}
</div>
</div>
<div className="ml-2 flex-shrink-0">
{checkingServers ? (
<McpStatusBadge status="checking" />
) : (
<McpStatusBadge status={isAvailable ? 'available' : 'unavailable'} />
)}
</div>
</div>
{/* Error message */}
{!isAvailable && mcpServer.error && (
<div className="mt-1.5 ml-6 text-xs text-red-600 dark:text-red-400">Error: {mcpServer.error}</div>
)}
{/* Tool list */}
{isExpanded && isAvailable && (
<div className="mt-2">
<div className="text-bolt-elements-textSecondary text-xs font-medium ml-1 mb-1.5">Available Tools:</div>
{serverTools.length === 0 ? (
<div className="ml-4 text-xs text-bolt-elements-textSecondary">No tools available</div>
) : (
<div className="mt-1 space-y-2">
{serverTools.map(([toolName, toolSchema]) => (
<McpServerListItem
key={`${serverName}-${toolName}`}
toolName={toolName}
toolSchema={toolSchema}
/>
))}
</div>
)}
</div>
)}
</div>
);
})}
</div>
);
}

View File

@@ -0,0 +1,70 @@
import type { Tool } from 'ai';
type ParameterProperty = {
type?: string;
description?: string;
};
type ToolParameters = {
jsonSchema: {
properties?: Record<string, ParameterProperty>;
required?: string[];
};
};
type McpToolProps = {
toolName: string;
toolSchema: Tool;
};
export default function McpServerListItem({ toolName, toolSchema }: McpToolProps) {
if (!toolSchema) {
return null;
}
const parameters = (toolSchema.parameters as ToolParameters)?.jsonSchema.properties || {};
const requiredParams = (toolSchema.parameters as ToolParameters)?.jsonSchema.required || [];
return (
<div className="mt-2 ml-4 p-3 rounded-md bg-bolt-elements-background-depth-2 text-xs">
<div className="flex flex-col gap-1.5">
<h3 className="text-bolt-elements-textPrimary font-semibold truncate" title={toolName}>
{toolName}
</h3>
<p className="text-bolt-elements-textSecondary">{toolSchema.description || 'No description available'}</p>
{Object.keys(parameters).length > 0 && (
<div className="mt-2.5">
<h4 className="text-bolt-elements-textSecondary font-semibold mb-1.5">Parameters:</h4>
<ul className="ml-1 space-y-2">
{Object.entries(parameters).map(([paramName, paramDetails]) => (
<li key={paramName} className="break-words">
<div className="flex items-start">
<span className="font-medium text-bolt-elements-textPrimary">
{paramName}
{requiredParams.includes(paramName) && (
<span className="text-red-600 dark:text-red-400 ml-1">*</span>
)}
</span>
<span className="mx-2 text-bolt-elements-textSecondary"></span>
<div className="flex-1">
{paramDetails.type && (
<span className="text-bolt-elements-textSecondary italic">{paramDetails.type}</span>
)}
{paramDetails.description && (
<div className="mt-0.5 text-bolt-elements-textSecondary">{paramDetails.description}</div>
)}
</div>
</div>
</li>
))}
</ul>
</div>
)}
</div>
</div>
);
}

View File

@@ -0,0 +1,37 @@
import { useMemo } from 'react';
export default function McpStatusBadge({ status }: { status: 'checking' | 'available' | 'unavailable' }) {
const { styles, label, icon, ariaLabel } = useMemo(() => {
const base = 'px-2 py-0.5 rounded-full text-xs font-medium flex items-center gap-1 transition-colors';
const config = {
checking: {
styles: `${base} bg-blue-100 text-blue-800 dark:bg-blue-900/80 dark:text-blue-200`,
label: 'Checking...',
ariaLabel: 'Checking server status',
icon: <span className="i-svg-spinners:90-ring-with-bg w-3 h-3 text-current animate-spin" aria-hidden="true" />,
},
available: {
styles: `${base} bg-green-100 text-green-800 dark:bg-green-900/80 dark:text-green-200`,
label: 'Available',
ariaLabel: 'Server available',
icon: <span className="i-ph:check-circle w-3 h-3 text-current" aria-hidden="true" />,
},
unavailable: {
styles: `${base} bg-red-100 text-red-800 dark:bg-red-900/80 dark:text-red-200`,
label: 'Unavailable',
ariaLabel: 'Server unavailable',
icon: <span className="i-ph:warning-circle w-3 h-3 text-current" aria-hidden="true" />,
},
};
return config[status];
}, [status]);
return (
<span className={styles} role="status" aria-live="polite" aria-label={ariaLabel}>
{icon}
{label}
</span>
);
}

View File

@@ -0,0 +1,239 @@
import { useEffect, useMemo, useState } from 'react';
import { classNames } from '~/utils/classNames';
import type { MCPConfig } from '~/lib/services/mcpService';
import { toast } from 'react-toastify';
import { useMCPStore } from '~/lib/stores/mcp';
import McpServerList from '~/components/@settings/tabs/mcp/McpServerList';
const EXAMPLE_MCP_CONFIG: MCPConfig = {
mcpServers: {
everything: {
type: 'stdio',
command: 'npx',
args: ['-y', '@modelcontextprotocol/server-everything'],
},
deepwiki: {
type: 'streamable-http',
url: 'https://mcp.deepwiki.com/mcp',
},
'local-sse': {
type: 'sse',
url: 'http://localhost:8000/sse',
headers: {
Authorization: 'Bearer mytoken123',
},
},
},
};
export default function McpTab() {
const settings = useMCPStore((state) => state.settings);
const isInitialized = useMCPStore((state) => state.isInitialized);
const serverTools = useMCPStore((state) => state.serverTools);
const initialize = useMCPStore((state) => state.initialize);
const updateSettings = useMCPStore((state) => state.updateSettings);
const checkServersAvailabilities = useMCPStore((state) => state.checkServersAvailabilities);
const [isSaving, setIsSaving] = useState(false);
const [mcpConfigText, setMCPConfigText] = useState('');
const [maxLLMSteps, setMaxLLMSteps] = useState(1);
const [error, setError] = useState<string | null>(null);
const [isCheckingServers, setIsCheckingServers] = useState(false);
const [expandedServer, setExpandedServer] = useState<string | null>(null);
useEffect(() => {
if (!isInitialized) {
initialize().catch((err) => {
setError(`Failed to initialize MCP settings: ${err instanceof Error ? err.message : String(err)}`);
toast.error('Failed to load MCP configuration');
});
}
}, [isInitialized]);
useEffect(() => {
setMCPConfigText(JSON.stringify(settings.mcpConfig, null, 2));
setMaxLLMSteps(settings.maxLLMSteps);
setError(null);
}, [settings]);
const parsedConfig = useMemo(() => {
try {
setError(null);
return JSON.parse(mcpConfigText) as MCPConfig;
} catch (e) {
setError(`Invalid JSON format: ${e instanceof Error ? e.message : String(e)}`);
return null;
}
}, [mcpConfigText]);
const handleMaxLLMCallChange = (value: string) => {
setMaxLLMSteps(parseInt(value, 10));
};
const handleSave = async () => {
if (!parsedConfig) {
return;
}
setIsSaving(true);
try {
await updateSettings({
mcpConfig: parsedConfig,
maxLLMSteps,
});
toast.success('MCP configuration saved');
setError(null);
} catch (e) {
setError(e instanceof Error ? e.message : 'Failed to save configuration');
toast.error('Failed to save MCP configuration');
} finally {
setIsSaving(false);
}
};
const handleLoadExample = () => {
setMCPConfigText(JSON.stringify(EXAMPLE_MCP_CONFIG, null, 2));
setError(null);
};
const checkServerAvailability = async () => {
if (serverEntries.length === 0) {
return;
}
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 serverEntries = useMemo(() => Object.entries(serverTools), [serverTools]);
return (
<div className="max-w-2xl mx-auto space-y-6">
<section aria-labelledby="server-status-heading">
<div className="flex justify-between items-center mb-3">
<h2 className="text-base font-medium text-bolt-elements-textPrimary">MCP Servers Configured</h2>{' '}
<button
onClick={checkServerAvailability}
disabled={isCheckingServers || !parsedConfig || 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>
<McpServerList
checkingServers={isCheckingServers}
expandedServer={expandedServer}
serverEntries={serverEntries}
toggleServerExpanded={toggleServerExpanded}
/>
</section>
<section aria-labelledby="config-section-heading">
<h2 className="text-base font-medium text-bolt-elements-textPrimary mb-3">Configuration</h2>
<div className="space-y-4">
<div>
<label htmlFor="mcp-config" className="block text-sm text-bolt-elements-textSecondary mb-2">
Configuration JSON
</label>
<textarea
id="mcp-config"
value={mcpConfigText}
onChange={(e) => setMCPConfigText(e.target.value)}
className={classNames(
'w-full px-3 py-2 rounded-lg text-sm font-mono h-72',
'bg-[#F8F8F8] dark:bg-[#1A1A1A]',
'border',
error ? 'border-bolt-elements-icon-error' : 'border-[#E5E5E5] dark:border-[#333333]',
'text-bolt-elements-textPrimary',
'focus:outline-none focus:ring-1 focus:ring-bolt-elements-focus',
)}
/>
</div>
<div>{error && <p className="mt-2 mb-2 text-sm text-bolt-elements-icon-error">{error}</p>}</div>
<div>
<label htmlFor="max-llm-steps" className="block text-sm text-bolt-elements-textSecondary mb-2">
Maximum number of sequential LLM calls (steps)
</label>
<input
id="max-llm-steps"
type="number"
placeholder="Maximum number of sequential LLM calls"
min="1"
max="20"
value={maxLLMSteps}
onChange={(e) => handleMaxLLMCallChange(e.target.value)}
className="w-full px-3 py-2 text-bolt-elements-textPrimary text-sm rounded-lg bg-white dark:bg-bolt-elements-background-depth-4 border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor-dark focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
</div>
<div className="mt-2 text-sm text-bolt-elements-textSecondary">
The MCP configuration format is identical to the one used in Claude Desktop.
<a
href="https://modelcontextprotocol.io/examples"
target="_blank"
rel="noopener noreferrer"
className="text-bolt-elements-link hover:underline inline-flex items-center gap-1"
>
View example servers
<div className="i-ph:arrow-square-out w-4 h-4" />
</a>
</div>
</div>
</section>
<div className="flex flex-wrap justify-between gap-3 mt-6">
<button
onClick={handleLoadExample}
className="px-4 py-2 rounded-lg text-sm border border-bolt-elements-borderColor
bg-bolt-elements-background-depth-2 text-bolt-elements-textSecondary
hover:bg-bolt-elements-background-depth-3"
>
Load Example
</button>
<div className="flex gap-2">
<button
onClick={handleSave}
disabled={isSaving || !parsedConfig}
aria-disabled={isSaving || !parsedConfig}
className={classNames(
'px-4 py-2 rounded-lg text-sm flex items-center gap-2',
'bg-bolt-elements-item-backgroundAccent text-bolt-elements-item-contentAccent',
'hover:bg-bolt-elements-item-backgroundActive',
'disabled:opacity-50 disabled:cursor-not-allowed',
)}
>
<div className="i-ph:floppy-disk w-4 h-4" />
{isSaving ? 'Saving...' : 'Save Configuration'}
</button>
</div>
</div>
</div>
);
}

View File

@@ -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>

View File

@@ -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;
}}

View File

@@ -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}
/>
);
},

View File

@@ -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>

View 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>
);
}

View File

@@ -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>

View 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>
);
});