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

View File

@@ -0,0 +1,457 @@
import {
experimental_createMCPClient,
type ToolSet,
type Message,
type DataStreamWriter,
convertToCoreMessages,
formatDataStreamPart,
} from 'ai';
import { Experimental_StdioMCPTransport } from 'ai/mcp-stdio';
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
import { z } from 'zod';
import type { ToolCallAnnotation } from '~/types/context';
import {
TOOL_EXECUTION_APPROVAL,
TOOL_EXECUTION_DENIED,
TOOL_EXECUTION_ERROR,
TOOL_NO_EXECUTE_FUNCTION,
} from '~/utils/constants';
import { createScopedLogger } from '~/utils/logger';
const logger = createScopedLogger('mcp-service');
export const stdioServerConfigSchema = z
.object({
type: z.enum(['stdio']).optional(),
command: z.string().min(1, 'Command cannot be empty'),
args: z.array(z.string()).optional(),
cwd: z.string().optional(),
env: z.record(z.string()).optional(),
})
.transform((data) => ({
...data,
type: 'stdio' as const,
}));
export type STDIOServerConfig = z.infer<typeof stdioServerConfigSchema>;
export const sseServerConfigSchema = z
.object({
type: z.enum(['sse']).optional(),
url: z.string().url('URL must be a valid URL format'),
headers: z.record(z.string()).optional(),
})
.transform((data) => ({
...data,
type: 'sse' as const,
}));
export type SSEServerConfig = z.infer<typeof sseServerConfigSchema>;
export const streamableHTTPServerConfigSchema = z
.object({
type: z.enum(['streamable-http']).optional(),
url: z.string().url('URL must be a valid URL format'),
headers: z.record(z.string()).optional(),
})
.transform((data) => ({
...data,
type: 'streamable-http' as const,
}));
export type StreamableHTTPServerConfig = z.infer<typeof streamableHTTPServerConfigSchema>;
export const mcpServerConfigSchema = z.union([
stdioServerConfigSchema,
sseServerConfigSchema,
streamableHTTPServerConfigSchema,
]);
export type MCPServerConfig = z.infer<typeof mcpServerConfigSchema>;
export const mcpConfigSchema = z.object({
mcpServers: z.record(z.string(), mcpServerConfigSchema),
});
export type MCPConfig = z.infer<typeof mcpConfigSchema>;
export type MCPClient = {
tools: () => Promise<ToolSet>;
close: () => Promise<void>;
} & {
serverName: string;
};
export type ToolCall = {
type: 'tool-call';
toolCallId: string;
toolName: string;
args: Record<string, unknown>;
};
export type MCPServerTools = Record<string, MCPServer>;
export type MCPServerAvailable = {
status: 'available';
tools: ToolSet;
client: MCPClient;
config: MCPServerConfig;
};
export type MCPServerUnavailable = {
status: 'unavailable';
error: string;
client: MCPClient | null;
config: MCPServerConfig;
};
export type MCPServer = MCPServerAvailable | MCPServerUnavailable;
export class MCPService {
private static _instance: MCPService;
private _tools: ToolSet = {};
private _toolsWithoutExecute: ToolSet = {};
private _mcpToolsPerServer: MCPServerTools = {};
private _toolNamesToServerNames = new Map<string, string>();
private _config: MCPConfig = {
mcpServers: {},
};
static getInstance(): MCPService {
if (!MCPService._instance) {
MCPService._instance = new MCPService();
}
return MCPService._instance;
}
private _validateServerConfig(serverName: string, config: any): MCPServerConfig {
const hasStdioField = config.command !== undefined;
const hasUrlField = config.url !== undefined;
if (hasStdioField && hasUrlField) {
throw new Error(`cannot have "command" and "url" defined for the same server.`);
}
if (!config.type && hasStdioField) {
config.type = 'stdio';
}
if (hasUrlField && !config.type) {
throw new Error(`missing "type" field, only "sse" and "streamable-http" are valid options.`);
}
if (!['stdio', 'sse', 'streamable-http'].includes(config.type)) {
throw new Error(`provided "type" is invalid, only "stdio", "sse" or "streamable-http" are valid options.`);
}
// Check for type/field mismatch
if (config.type === 'stdio' && !hasStdioField) {
throw new Error(`missing "command" field.`);
}
if (['sse', 'streamable-http'].includes(config.type) && !hasUrlField) {
throw new Error(`missing "url" field.`);
}
try {
return mcpServerConfigSchema.parse(config);
} catch (validationError) {
if (validationError instanceof z.ZodError) {
const errorMessages = validationError.errors.map((err) => `${err.path.join('.')}: ${err.message}`).join('; ');
throw new Error(`Invalid configuration for server "${serverName}": ${errorMessages}`);
}
throw validationError;
}
}
async updateConfig(config: MCPConfig) {
logger.debug('updating config', JSON.stringify(config));
this._config = config;
await this._createClients();
return this._mcpToolsPerServer;
}
private async _createStreamableHTTPClient(
serverName: string,
config: StreamableHTTPServerConfig,
): Promise<MCPClient> {
logger.debug(`Creating Streamable-HTTP client for ${serverName} with URL: ${config.url}`);
const client = await experimental_createMCPClient({
transport: new StreamableHTTPClientTransport(new URL(config.url), {
requestInit: {
headers: config.headers,
},
}),
});
return Object.assign(client, { serverName });
}
private async _createSSEClient(serverName: string, config: SSEServerConfig): Promise<MCPClient> {
logger.debug(`Creating SSE client for ${serverName} with URL: ${config.url}`);
const client = await experimental_createMCPClient({
transport: config,
});
return Object.assign(client, { serverName });
}
private async _createStdioClient(serverName: string, config: STDIOServerConfig): Promise<MCPClient> {
logger.debug(
`Creating STDIO client for '${serverName}' with command: '${config.command}' ${config.args?.join(' ') || ''}`,
);
const client = await experimental_createMCPClient({ transport: new Experimental_StdioMCPTransport(config) });
return Object.assign(client, { serverName });
}
private _registerTools(serverName: string, tools: ToolSet) {
for (const [toolName, tool] of Object.entries(tools)) {
if (this._tools[toolName]) {
const existingServerName = this._toolNamesToServerNames.get(toolName);
if (existingServerName && existingServerName !== serverName) {
logger.warn(`Tool conflict: "${toolName}" from "${serverName}" overrides tool from "${existingServerName}"`);
}
}
this._tools[toolName] = tool;
this._toolsWithoutExecute[toolName] = { ...tool, execute: undefined };
this._toolNamesToServerNames.set(toolName, serverName);
}
}
private async _createMCPClient(serverName: string, serverConfig: MCPServerConfig): Promise<MCPClient> {
const validatedConfig = this._validateServerConfig(serverName, serverConfig);
if (validatedConfig.type === 'stdio') {
return await this._createStdioClient(serverName, serverConfig as STDIOServerConfig);
} else if (validatedConfig.type === 'sse') {
return await this._createSSEClient(serverName, serverConfig as SSEServerConfig);
} else {
return await this._createStreamableHTTPClient(serverName, serverConfig as StreamableHTTPServerConfig);
}
}
private async _createClients() {
await this._closeClients();
const createClientPromises = Object.entries(this._config?.mcpServers || []).map(async ([serverName, config]) => {
let client: MCPClient | null = null;
try {
client = await this._createMCPClient(serverName, config);
try {
const tools = await client.tools();
this._registerTools(serverName, tools);
this._mcpToolsPerServer[serverName] = {
status: 'available',
client,
tools,
config,
};
} catch (error) {
logger.error(`Failed to get tools from server ${serverName}:`, error);
this._mcpToolsPerServer[serverName] = {
status: 'unavailable',
error: 'could not retrieve tools from server',
client,
config,
};
}
} catch (error) {
logger.error(`Failed to initialize MCP client for server: ${serverName}`, error);
this._mcpToolsPerServer[serverName] = {
status: 'unavailable',
error: (error as Error).message,
client,
config,
};
}
});
await Promise.allSettled(createClientPromises);
}
async checkServersAvailabilities() {
this._tools = {};
this._toolsWithoutExecute = {};
this._toolNamesToServerNames.clear();
const checkPromises = Object.entries(this._mcpToolsPerServer).map(async ([serverName, server]) => {
let client = server.client;
try {
logger.debug(`Checking MCP server "${serverName}" availability: start`);
if (!client) {
client = await this._createMCPClient(serverName, this._config?.mcpServers[serverName]);
}
try {
const tools = await client.tools();
this._registerTools(serverName, tools);
this._mcpToolsPerServer[serverName] = {
status: 'available',
client,
tools,
config: server.config,
};
} catch (error) {
logger.error(`Failed to get tools from server ${serverName}:`, error);
this._mcpToolsPerServer[serverName] = {
status: 'unavailable',
error: 'could not retrieve tools from server',
client,
config: server.config,
};
}
logger.debug(`Checking MCP server "${serverName}" availability: end`);
} catch (error) {
logger.error(`Failed to connect to server ${serverName}:`, error);
this._mcpToolsPerServer[serverName] = {
status: 'unavailable',
error: 'could not connect to server',
client,
config: server.config,
};
}
});
await Promise.allSettled(checkPromises);
return this._mcpToolsPerServer;
}
private async _closeClients(): Promise<void> {
const closePromises = Object.entries(this._mcpToolsPerServer).map(async ([serverName, server]) => {
if (!server.client) {
return;
}
logger.debug(`Closing client for server "${serverName}"`);
try {
await server.client.close();
} catch (error) {
logger.error(`Error closing client for ${serverName}:`, error);
}
});
await Promise.allSettled(closePromises);
this._tools = {};
this._toolsWithoutExecute = {};
this._mcpToolsPerServer = {};
this._toolNamesToServerNames.clear();
}
isValidToolName(toolName: string): boolean {
return toolName in this._tools;
}
processToolCall(toolCall: ToolCall, dataStream: DataStreamWriter): void {
const { toolCallId, toolName } = toolCall;
if (this.isValidToolName(toolName)) {
const { description = 'No description available' } = this.toolsWithoutExecute[toolName];
const serverName = this._toolNamesToServerNames.get(toolName);
if (serverName) {
dataStream.writeMessageAnnotation({
type: 'toolCall',
toolCallId,
serverName,
toolName,
toolDescription: description,
} satisfies ToolCallAnnotation);
}
}
}
async processToolInvocations(messages: Message[], dataStream: DataStreamWriter): Promise<Message[]> {
const lastMessage = messages[messages.length - 1];
const parts = lastMessage.parts;
if (!parts) {
return messages;
}
const processedParts = await Promise.all(
parts.map(async (part) => {
// Only process tool invocations parts
if (part.type !== 'tool-invocation') {
return part;
}
const { toolInvocation } = part;
const { toolName, toolCallId } = toolInvocation;
// return part as-is if tool does not exist, or if it's not a tool call result
if (!this.isValidToolName(toolName) || toolInvocation.state !== 'result') {
return part;
}
let result;
if (toolInvocation.result === TOOL_EXECUTION_APPROVAL.APPROVE) {
const toolInstance = this._tools[toolName];
if (toolInstance && typeof toolInstance.execute === 'function') {
logger.debug(`calling tool "${toolName}" with args: ${JSON.stringify(toolInvocation.args)}`);
try {
result = await toolInstance.execute(toolInvocation.args, {
messages: convertToCoreMessages(messages),
toolCallId,
});
} catch (error) {
logger.error(`error while calling tool "${toolName}":`, error);
result = TOOL_EXECUTION_ERROR;
}
} else {
result = TOOL_NO_EXECUTE_FUNCTION;
}
} else if (toolInvocation.result === TOOL_EXECUTION_APPROVAL.REJECT) {
result = TOOL_EXECUTION_DENIED;
} else {
// For any unhandled responses, return the original part.
return part;
}
// Forward updated tool result to the client.
dataStream.write(
formatDataStreamPart('tool_result', {
toolCallId,
result,
}),
);
// Return updated toolInvocation with the actual result.
return {
...part,
toolInvocation: {
...toolInvocation,
result,
},
};
}),
);
// Finally return the processed messages
return [...messages.slice(0, -1), { ...lastMessage, parts: processedParts }];
}
get tools() {
return this._tools;
}
get toolsWithoutExecute() {
return this._toolsWithoutExecute;
}
}

115
app/lib/stores/mcp.ts Normal file
View File

@@ -0,0 +1,115 @@
import { create } from 'zustand';
import type { MCPConfig, MCPServerTools } from '~/lib/services/mcpService';
const MCP_SETTINGS_KEY = 'mcp_settings';
const isBrowser = typeof window !== 'undefined';
type MCPSettings = {
mcpConfig: MCPConfig;
maxLLMSteps: number;
};
const defaultSettings = {
maxLLMSteps: 5,
mcpConfig: {
mcpServers: {},
},
} satisfies MCPSettings;
type Store = {
isInitialized: boolean;
settings: MCPSettings;
serverTools: MCPServerTools;
error: string | null;
isUpdatingConfig: boolean;
};
type Actions = {
initialize: () => Promise<void>;
updateSettings: (settings: MCPSettings) => Promise<void>;
checkServersAvailabilities: () => Promise<void>;
};
export const useMCPStore = create<Store & Actions>((set, get) => ({
isInitialized: false,
settings: defaultSettings,
serverTools: {},
error: null,
isUpdatingConfig: false,
initialize: async () => {
if (get().isInitialized) {
return;
}
if (isBrowser) {
const savedConfig = localStorage.getItem(MCP_SETTINGS_KEY);
if (savedConfig) {
try {
const settings = JSON.parse(savedConfig) as MCPSettings;
const serverTools = await updateServerConfig(settings.mcpConfig);
set(() => ({ settings, serverTools }));
} catch (error) {
console.error('Error parsing saved mcp config:', error);
set(() => ({
error: `Error parsing saved mcp config: ${error instanceof Error ? error.message : String(error)}`,
}));
}
} else {
localStorage.setItem(MCP_SETTINGS_KEY, JSON.stringify(defaultSettings));
}
}
set(() => ({ isInitialized: true }));
},
updateSettings: async (newSettings: MCPSettings) => {
if (get().isUpdatingConfig) {
return;
}
try {
set(() => ({ isUpdatingConfig: true }));
const serverTools = await updateServerConfig(newSettings.mcpConfig);
if (isBrowser) {
localStorage.setItem(MCP_SETTINGS_KEY, JSON.stringify(newSettings));
}
set(() => ({ settings: newSettings, serverTools }));
} catch (error) {
throw error;
} finally {
set(() => ({ isUpdatingConfig: false }));
}
},
checkServersAvailabilities: async () => {
const response = await fetch('/api/mcp-check', {
method: 'GET',
});
if (!response.ok) {
throw new Error(`Server responded with ${response.status}: ${response.statusText}`);
}
const serverTools = (await response.json()) as MCPServerTools;
set(() => ({ serverTools }));
},
}));
async function updateServerConfig(config: MCPConfig) {
const response = await fetch('/api/mcp-update-config', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(config),
});
if (!response.ok) {
throw new Error(`Server responded with ${response.status}: ${response.statusText}`);
}
const data = (await response.json()) as MCPServerTools;
return data;
}

View File

@@ -12,6 +12,7 @@ import { WORK_DIR } from '~/utils/constants';
import { createSummary } from '~/lib/.server/llm/create-summary';
import { extractPropertiesFromMessage } from '~/lib/.server/llm/utils';
import type { DesignScheme } from '~/types/design-scheme';
import { MCPService } from '~/lib/services/mcpService';
export async function action(args: ActionFunctionArgs) {
return chatAction(args);
@@ -38,22 +39,24 @@ function parseCookies(cookieHeader: string): Record<string, string> {
}
async function chatAction({ context, request }: ActionFunctionArgs) {
const { messages, files, promptId, contextOptimization, supabase, chatMode, designScheme } = await request.json<{
messages: Messages;
files: any;
promptId?: string;
contextOptimization: boolean;
chatMode: 'discuss' | 'build';
designScheme?: DesignScheme;
supabase?: {
isConnected: boolean;
hasSelectedProject: boolean;
credentials?: {
anonKey?: string;
supabaseUrl?: string;
const { messages, files, promptId, contextOptimization, supabase, chatMode, designScheme, maxLLMSteps } =
await request.json<{
messages: Messages;
files: any;
promptId?: string;
contextOptimization: boolean;
chatMode: 'discuss' | 'build';
designScheme?: DesignScheme;
supabase?: {
isConnected: boolean;
hasSelectedProject: boolean;
credentials?: {
anonKey?: string;
supabaseUrl?: string;
};
};
};
}>();
maxLLMSteps: number;
}>();
const cookieHeader = request.headers.get('Cookie');
const apiKeys = JSON.parse(parseCookies(cookieHeader || '').apiKeys || '{}');
@@ -72,6 +75,7 @@ async function chatAction({ context, request }: ActionFunctionArgs) {
let progressCounter: number = 1;
try {
const mcpService = MCPService.getInstance();
const totalMessageContent = messages.reduce((acc, message) => acc + message.content, '');
logger.debug(`Total message length: ${totalMessageContent.split(' ').length}, words`);
@@ -84,8 +88,10 @@ async function chatAction({ context, request }: ActionFunctionArgs) {
let summary: string | undefined = undefined;
let messageSliceId = 0;
if (messages.length > 3) {
messageSliceId = messages.length - 3;
const processedMessage = await mcpService.processToolInvocations(messages, dataStream);
if (processedMessage.length > 3) {
messageSliceId = processedMessage.length - 3;
}
if (filePaths.length > 0 && contextOptimization) {
@@ -99,10 +105,10 @@ async function chatAction({ context, request }: ActionFunctionArgs) {
} satisfies ProgressAnnotation);
// Create a summary of the chat
console.log(`Messages count: ${messages.length}`);
console.log(`Messages count: ${processedMessage.length}`);
summary = await createSummary({
messages: [...messages],
messages: [...processedMessage],
env: context.cloudflare?.env,
apiKeys,
providerSettings,
@@ -128,7 +134,7 @@ async function chatAction({ context, request }: ActionFunctionArgs) {
dataStream.writeMessageAnnotation({
type: 'chatSummary',
summary,
chatId: messages.slice(-1)?.[0]?.id,
chatId: processedMessage.slice(-1)?.[0]?.id,
} as ContextAnnotation);
// Update context buffer
@@ -142,9 +148,9 @@ async function chatAction({ context, request }: ActionFunctionArgs) {
} satisfies ProgressAnnotation);
// Select context files
console.log(`Messages count: ${messages.length}`);
console.log(`Messages count: ${processedMessage.length}`);
filteredFiles = await selectContext({
messages: [...messages],
messages: [...processedMessage],
env: context.cloudflare?.env,
apiKeys,
files,
@@ -192,7 +198,15 @@ async function chatAction({ context, request }: ActionFunctionArgs) {
const options: StreamingOptions = {
supabaseConnection: supabase,
toolChoice: 'none',
toolChoice: 'auto',
tools: mcpService.toolsWithoutExecute,
maxSteps: maxLLMSteps,
onStepFinish: ({ toolCalls }) => {
// add tool call annotations for frontend processing
toolCalls.forEach((toolCall) => {
mcpService.processToolCall(toolCall, dataStream);
});
},
onFinish: async ({ text: content, finishReason, usage }) => {
logger.debug('usage', JSON.stringify(usage));
@@ -232,17 +246,17 @@ async function chatAction({ context, request }: ActionFunctionArgs) {
logger.info(`Reached max token limit (${MAX_TOKENS}): Continuing message (${switchesLeft} switches left)`);
const lastUserMessage = messages.filter((x) => x.role == 'user').slice(-1)[0];
const lastUserMessage = processedMessage.filter((x) => x.role == 'user').slice(-1)[0];
const { model, provider } = extractPropertiesFromMessage(lastUserMessage);
messages.push({ id: generateId(), role: 'assistant', content });
messages.push({
processedMessage.push({ id: generateId(), role: 'assistant', content });
processedMessage.push({
id: generateId(),
role: 'user',
content: `[Model: ${model}]\n\n[Provider: ${provider}]\n\n${CONTINUE_PROMPT}`,
});
const result = await streamText({
messages,
messages: [...processedMessage],
env: context.cloudflare?.env,
options,
apiKeys,
@@ -283,7 +297,7 @@ async function chatAction({ context, request }: ActionFunctionArgs) {
} satisfies ProgressAnnotation);
const result = await streamText({
messages,
messages: [...processedMessage],
env: context.cloudflare?.env,
options,
apiKeys,

View File

@@ -0,0 +1,16 @@
import { createScopedLogger } from '~/utils/logger';
import { MCPService } from '~/lib/services/mcpService';
const logger = createScopedLogger('api.mcp-check');
export async function loader() {
try {
const mcpService = MCPService.getInstance();
const serverTools = await mcpService.checkServersAvailabilities();
return Response.json(serverTools);
} catch (error) {
logger.error('Error checking MCP servers:', error);
return Response.json({ error: 'Failed to check MCP servers' }, { status: 500 });
}
}

View File

@@ -0,0 +1,23 @@
import { type ActionFunctionArgs } from '@remix-run/cloudflare';
import { createScopedLogger } from '~/utils/logger';
import { MCPService, type MCPConfig } from '~/lib/services/mcpService';
const logger = createScopedLogger('api.mcp-update-config');
export async function action({ request }: ActionFunctionArgs) {
try {
const mcpConfig = (await request.json()) as MCPConfig;
if (!mcpConfig || typeof mcpConfig !== 'object') {
return Response.json({ error: 'Invalid MCP servers configuration' }, { status: 400 });
}
const mcpService = MCPService.getInstance();
const serverTools = await mcpService.updateConfig(mcpConfig);
return Response.json(serverTools);
} catch (error) {
logger.error('Error updating MCP config:', error);
return Response.json({ error: 'Failed to update MCP config' }, { status: 500 });
}
}

View File

@@ -3,7 +3,7 @@
}
.shiki {
&:not(:has(.actions), .actions *) {
&:not(:has(.actions), .actions *, .mcp-tool-invocation-code *) {
background-color: var(--bolt-elements-messages-code-background) !important;
}
}

View File

@@ -16,3 +16,11 @@ export type ProgressAnnotation = {
order: number;
message: string;
};
export type ToolCallAnnotation = {
type: 'toolCall';
toolCallId: string;
serverName: string;
toolName: string;
toolDescription: string;
};

View File

@@ -8,6 +8,13 @@ export const MODEL_REGEX = /^\[Model: (.*?)\]\n\n/;
export const PROVIDER_REGEX = /\[Provider: (.*?)\]\n\n/;
export const DEFAULT_MODEL = 'claude-3-5-sonnet-latest';
export const PROMPT_COOKIE_KEY = 'cachedPrompt';
export const TOOL_EXECUTION_APPROVAL = {
APPROVE: 'Yes, approved.',
REJECT: 'No, rejected.',
} as const;
export const TOOL_NO_EXECUTE_FUNCTION = 'Error: No execute function found on tool';
export const TOOL_EXECUTION_DENIED = 'Error: User denied access to tool execution';
export const TOOL_EXECUTION_ERROR = 'Error: An error occured while calling tool';
const llmManager = LLMManager.getInstance(import.meta.env);