Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

MCP UI: tool servers screen, per-kwant tools, readable approvals and tool calls

Lin (kwant bot)b99c02d059dc
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 70d44fbd..68ec7f2e 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -4,6 +4,7 @@ import { Sidebar, Kwant, Channel, Team, memberIdsOf } from './components/Sidebar
import { ChatView, ChatMessage, DiscussionState, RoutingState } from './components/ChatView';
import { PendingApproval } from './components/ModernApprovalCard';
import { SettingsModal } from './components/SettingsModal';
+import { McpServersModal } from './components/McpServersModal';
import { NewAgentModal, AgentFormData } from './components/NewAgentModal';
import { NewTeamModal } from './components/NewTeamModal';
import { ManageTeamModal } from './components/ManageTeamModal';
@@ -49,6 +50,7 @@ export const App: React.FC = () => {
// Modals state
const [isSettingsOpen, setIsSettingsOpen] = useState(false);
+ const [isMcpOpen, setIsMcpOpen] = useState(false);
const [isNewAgentOpen, setIsNewAgentOpen] = useState(false);
// Team that a newly created agent should join (set by a team's "Add member")
const [newAgentTeam, setNewAgentTeam] = useState<Team | null>(null);
@@ -600,12 +602,23 @@ export const App: React.FC = () => {
playSfx('click');
};
+ const saveKwantMcpServers = async (kwantId: string, serverIds: string[] | undefined): Promise<string | void> => {
+ if (serverIds === undefined) return;
+ const res = await fetch(`/api/kwants/${kwantId}/mcp-servers`, {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ server_ids: serverIds }),
+ });
+ if (!res.ok) return `Saved, but the tool servers couldn't be updated (HTTP ${res.status}).`;
+ };
+
const handleUpdateAgent = async (kwant: Kwant, agentData: AgentFormData): Promise<string | void> => {
try {
+ const { mcp_server_ids, ...kwantData } = agentData;
const res = await fetch(`/api/kwants/${kwant.id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(agentData),
+ body: JSON.stringify(kwantData),
});
if (res.status === 409) return `Another agent is already named "${agentData.name}".`;
if (res.status === 400) return 'Name cannot be empty or contain spaces or @.';
@@ -623,6 +636,8 @@ export const App: React.FC = () => {
}
setMessages((prev) => rename(prev));
}
+ const mcpError = await saveKwantMcpServers(updated.id, mcp_server_ids);
+ if (mcpError) return mcpError;
playSfx('click');
} catch (err) {
console.error('Failed updating Agent:', err);
@@ -649,6 +664,10 @@ export const App: React.FC = () => {
if (res.ok) {
const created: Kwant = await res.json();
setKwants((prev) => [...prev, created]);
+ if (agentData.mcp_server_ids?.length) {
+ const mcpError = await saveKwantMcpServers(created.id, agentData.mcp_server_ids);
+ if (mcpError) console.error(mcpError);
+ }
setIsNewAgentOpen(false);
playSfx('fanfare');
const team = newAgentTeam && (teams.find((t) => t.id === newAgentTeam.id) ?? newAgentTeam);
@@ -1012,6 +1031,7 @@ export const App: React.FC = () => {
{/* Modern App Header */}
<AppHeader
onOpenSettings={() => setIsSettingsOpen(true)}
+ onOpenTools={() => setIsMcpOpen(true)}
tokensUsed={tokensUsed}
activeModel={currentKwant?.preferred_model || 'auto'}
/>
@@ -1108,6 +1128,7 @@ export const App: React.FC = () => {
}}
joinTeamName={newAgentTeam?.name}
takenNames={kwants.map((k) => k.name)}
+ onManageServers={() => setIsMcpOpen(true)}
onSubmit={handleCreateAgent}
/>
@@ -1115,6 +1136,8 @@ export const App: React.FC = () => {
<NewAgentModal
isOpen={!!editingKwant}
initial={editingKwant}
+ kwantId={editingKwant?.id}
+ onManageServers={() => setIsMcpOpen(true)}
onClose={() => setEditingKwant(null)}
onSubmit={(data) => (editingKwant ? handleUpdateAgent(editingKwant, data) : undefined)}
/>
@@ -1141,7 +1164,14 @@ export const App: React.FC = () => {
<SettingsModal
isOpen={isSettingsOpen}
onClose={() => setIsSettingsOpen(false)}
+ onOpenTools={() => {
+ setIsSettingsOpen(false);
+ setIsMcpOpen(true);
+ }}
/>
+
+ {/* MCP tool servers (opened last so it sits above the agent modal) */}
+ <McpServersModal isOpen={isMcpOpen} onClose={() => setIsMcpOpen(false)} />
</div>
);
};
diff --git a/frontend/src/components/AppHeader.tsx b/frontend/src/components/AppHeader.tsx
index efcdf69c..e669b7df 100644
--- a/frontend/src/components/AppHeader.tsx
+++ b/frontend/src/components/AppHeader.tsx
@@ -1,10 +1,11 @@
import React from 'react';
-import { Settings, Volume2, VolumeX, Cpu } from 'lucide-react';
+import { Settings, Volume2, VolumeX, Cpu, Plug } from 'lucide-react';
import { ModernAvatar } from './ModernAvatar';
import { isSfxMuted, toggleSfxMute, playSfx } from '../audio/chiptune';
interface AppHeaderProps {
onOpenSettings: () => void;
+ onOpenTools: () => void;
tokensUsed: number;
activeModel?: string;
}
@@ -65,6 +66,7 @@ const layaPill = (status: LayaStatus | null, activeModel: string) => {
export const AppHeader: React.FC<AppHeaderProps> = ({
onOpenSettings,
+ onOpenTools,
tokensUsed,
activeModel = 'auto',
}) => {
@@ -121,6 +123,20 @@ export const AppHeader: React.FC<AppHeaderProps> = ({
{sfxMuted ? <VolumeX size={17} /> : <Volume2 size={17} />}
</button>
+ {/* MCP Tools Button */}
+ <button
+ onClick={() => {
+ playSfx('click');
+ onOpenTools();
+ }}
+ title="Tool servers (MCP) your kwants can use"
+ aria-label="Tools"
+ className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs font-medium text-zinc-200 bg-zinc-800 hover:bg-zinc-700/80 border border-zinc-700/60 transition-all hover:border-zinc-600 shadow-sm"
+ >
+ <Plug size={14} className="text-sky-400" />
+ <span className="hidden sm:inline">Tools</span>
+ </button>
+
{/* Settings Button */}
<button
onClick={() => {
diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsx
index 767e4800..bd9b65d8 100644
--- a/frontend/src/components/ChatView.tsx
+++ b/frontend/src/components/ChatView.tsx
@@ -4,6 +4,7 @@ import { ModernAvatar } from './ModernAvatar';
import { ModernApprovalCard, PendingApproval } from './ModernApprovalCard';
import { MentionPopover, MentionItem } from './MentionPopover';
import { MarkdownRenderer } from './MarkdownRenderer';
+import { ToolCallsList } from './ToolCallsList';
import { VirtualMachinePane, TerminalLogEntry } from './VirtualMachinePane';
import { playSfx } from '../audio/chiptune';
import { groupDiscussionThreads, stripDiscussionMarkers } from '../discussionThreads';
@@ -473,6 +474,8 @@ export const ChatView: React.FC<ChatViewProps> = ({
)}
</div>
+ {!isUser && msg.tool_calls && <ToolCallsList raw={msg.tool_calls} />}
+
{/* Copy action */}
{!isUser && (
<div className="mt-1.5 flex items-center gap-2 text-zinc-500 text-xs">
diff --git a/frontend/src/components/KwantToolsPicker.tsx b/frontend/src/components/KwantToolsPicker.tsx
new file mode 100644
index 00000000..6e406c93
--- /dev/null
+++ b/frontend/src/components/KwantToolsPicker.tsx
@@ -0,0 +1,112 @@
+import React, { useEffect, useState } from 'react';
+import { Plug, Terminal, Globe, Info, Loader2 } from 'lucide-react';
+import { McpServer, EngineKeys, mcpSupportFor } from '../mcp';
+
+interface KwantToolsPickerProps {
+ /** Engine the kwant runs on (preferred_model), to say honestly when tools won't work. */
+ model: string;
+ selected: string[];
+ onChange: (ids: string[]) => void;
+ onManageServers?: () => void;
+}
+
+/** "Tools this kwant can use": one switch per registered MCP server. */
+export const KwantToolsPicker: React.FC<KwantToolsPickerProps> = ({ model, selected, onChange, onManageServers }) => {
+ const [servers, setServers] = useState<McpServer[] | null>(null);
+ const [keys, setKeys] = useState<EngineKeys>({ anthropic: false, openai: false, xai: false });
+
+ useEffect(() => {
+ let cancelled = false;
+ fetch('/api/mcp/servers')
+ .then((r) => (r.ok ? r.json() : []))
+ .then((list: McpServer[]) => !cancelled && setServers(list))
+ .catch(() => !cancelled && setServers([]));
+ fetch('/api/settings')
+ .then((r) => r.json())
+ .then(
+ (s) =>
+ !cancelled &&
+ setKeys({ anthropic: !!s.anthropic_api_key, openai: !!s.openai_api_key, xai: !!s.xai_api_key }),
+ )
+ .catch(() => undefined);
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
+ const support = mcpSupportFor(model, keys);
+ const toggle = (id: string) =>
+ onChange(selected.includes(id) ? selected.filter((s) => s !== id) : [...selected, id]);
+
+ return (
+ <div>
+ <div className="flex items-center justify-between mb-1">
+ <label className="text-xs font-medium text-zinc-400">
+ Tools this kwant can use <span className="text-zinc-600 font-normal">· asks you before each use</span>
+ </label>
+ {onManageServers && servers && servers.length > 0 && (
+ <button type="button" onClick={onManageServers} className="text-[11px] text-sky-300 hover:text-sky-200">
+ Manage servers
+ </button>
+ )}
+ </div>
+
+ {support.note && (
+ <p
+ className={`mb-1.5 flex items-start gap-1.5 px-2.5 py-2 rounded-lg border text-[11px] leading-snug ${
+ support.supported
+ ? 'bg-zinc-950/60 border-zinc-800 text-zinc-400'
+ : 'bg-amber-500/5 border-amber-500/20 text-amber-200/90'
+ }`}
+ >
+ <Info size={13} className={`flex-shrink-0 mt-px ${support.supported ? 'text-zinc-500' : 'text-amber-400'}`} />
+ <span>{support.note}</span>
+ </p>
+ )}
+
+ {servers === null ? (
+ <div className="py-3 flex justify-center text-zinc-500">
+ <Loader2 size={16} className="animate-spin" aria-label="Loading tool servers" />
+ </div>
+ ) : servers.length === 0 ? (
+ <div className="flex items-center justify-between gap-2 px-3 py-2.5 rounded-lg border border-dashed border-zinc-800 text-[11px] text-zinc-500">
+ <span className="flex items-center gap-1.5">
+ <Plug size={13} />
+ No tool servers yet.
+ </span>
+ {onManageServers && (
+ <button type="button" onClick={onManageServers} className="font-medium text-sky-300 hover:text-sky-200">
+ Add one
+ </button>
+ )}
+ </div>
+ ) : (
+ <ul className={`rounded-lg border border-zinc-800 divide-y divide-zinc-800/80 bg-zinc-950/60 ${support.supported ? '' : 'opacity-60'}`}>
+ {servers.map((s) => {
+ const on = selected.includes(s.id);
+ return (
+ <li key={s.id}>
+ <button
+ type="button"
+ role="switch"
+ aria-checked={on}
+ onClick={() => toggle(s.id)}
+ className="w-full flex items-center gap-2.5 px-3 py-2 text-left hover:bg-zinc-900/60 transition-colors"
+ >
+ <span className="text-zinc-500">{s.transport === 'stdio' ? <Terminal size={13} /> : <Globe size={13} />}</span>
+ <span className="flex-1 min-w-0">
+ <span className="block text-xs text-zinc-200 truncate">{s.name}</span>
+ {!s.enabled && <span className="block text-[10px] text-zinc-500">Paused, so it won’t be offered until it’s turned on</span>}
+ </span>
+ <span className={`relative flex-shrink-0 w-8 h-[18px] rounded-full transition-colors ${on ? 'bg-sky-600' : 'bg-zinc-700'}`}>
+ <span className={`absolute top-0.5 w-3.5 h-3.5 rounded-full bg-white shadow transition-all ${on ? 'left-[16px]' : 'left-0.5'}`} />
+ </span>
+ </button>
+ </li>
+ );
+ })}
+ </ul>
+ )}
+ </div>
+ );
+};
diff --git a/frontend/src/components/McpServersModal.tsx b/frontend/src/components/McpServersModal.tsx
new file mode 100644
index 00000000..1d4e97c4
--- /dev/null
+++ b/frontend/src/components/McpServersModal.tsx
@@ -0,0 +1,768 @@
+import React, { useCallback, useEffect, useState } from 'react';
+import {
+ Plug,
+ Terminal,
+ Globe,
+ Plus,
+ Trash2,
+ Pencil,
+ Loader2,
+ CheckCircle2,
+ AlertCircle,
+ X,
+ ShieldAlert,
+ Eye,
+ EyeOff,
+ ChevronLeft,
+ Wrench,
+ Sparkles,
+ CircleDashed,
+ PauseCircle,
+ Zap,
+} from 'lucide-react';
+import { playSfx } from '../audio/chiptune';
+import {
+ McpServer,
+ McpFormState,
+ McpTestResult,
+ McpTransport,
+ SecretRow,
+ StoredStatus,
+ MCP_PRESETS,
+ emptyMcpForm,
+ formToPayload,
+ serverToForm,
+ serverTarget,
+ splitCommandLine,
+ validateMcpForm,
+ loadStatuses,
+ saveStatuses,
+ humanizeToolName,
+} from '../mcp';
+
+interface McpServersModalProps {
+ isOpen: boolean;
+ onClose: () => void;
+}
+
+const inputCls =
+ 'w-full bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 text-xs text-zinc-100 placeholder-zinc-600 focus:border-sky-500 focus:outline-none transition-colors';
+
+const TRANSPORTS: Array<{ id: McpTransport; title: string; blurb: string; icon: React.ReactNode }> = [
+ { id: 'stdio', title: 'Runs on this machine', blurb: 'kwnt starts a command, like npx or uvx', icon: <Terminal size={18} /> },
+ { id: 'http', title: 'Connects to a URL', blurb: 'A server already running somewhere else', icon: <Globe size={18} /> },
+];
+
+const readError = async (res: Response) => {
+ try {
+ const body = await res.json();
+ if (body?.error) return String(body.error);
+ } catch {
+ // not JSON
+ }
+ return `Something went wrong (HTTP ${res.status}).`;
+};
+
+const StatusPill: React.FC<{ server: McpServer; status?: StoredStatus; testing: boolean }> = ({ server, status, testing }) => {
+ let cls = 'bg-zinc-800/60 text-zinc-400 border-zinc-700/60';
+ let icon = <CircleDashed size={11} />;
+ let label = 'Not tested yet';
+ if (testing) {
+ cls = 'bg-sky-500/10 text-sky-300 border-sky-500/20';
+ icon = <Loader2 size={11} className="animate-spin" />;
+ label = 'Testing…';
+ } else if (!server.enabled) {
+ cls = 'bg-zinc-800/60 text-zinc-400 border-zinc-700/60';
+ icon = <PauseCircle size={11} />;
+ label = 'Paused';
+ } else if (status?.ok) {
+ cls = 'bg-emerald-500/10 text-emerald-300 border-emerald-500/20';
+ icon = <CheckCircle2 size={11} />;
+ label = `Working · ${status.tools.length} ${status.tools.length === 1 ? 'tool' : 'tools'}`;
+ } else if (status && !status.ok) {
+ cls = 'bg-rose-500/10 text-rose-300 border-rose-500/20';
+ icon = <AlertCircle size={11} />;
+ label = 'Couldn’t connect';
+ }
+ return (
+ <span className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full border text-[10px] font-medium whitespace-nowrap ${cls}`}>
+ {icon}
+ {label}
+ </span>
+ );
+};
+
+const SecretRows: React.FC<{
+ rows: SecretRow[];
+ onChange: (rows: SecretRow[]) => void;
+ keyPlaceholder: string;
+ keyLabel: string;
+ addLabel: string;
+}> = ({ rows, onChange, keyPlaceholder, keyLabel, addLabel }) => {
+ const [shown, setShown] = useState<Record<number, boolean>>({});
+ const update = (i: number, patch: Partial<SecretRow>) => onChange(rows.map((r, j) => (j === i ? { ...r, ...patch } : r)));
+ return (
+ <div className="space-y-1.5">
+ {rows.map((row, i) => (
+ <div key={i} className="flex flex-col sm:flex-row gap-1.5">
+ <input
+ aria-label={keyLabel}
+ value={row.key}
+ disabled={row.saved}
+ onChange={(e) => update(i, { key: e.target.value })}
+ placeholder={keyPlaceholder}
+ className={`${inputCls} sm:w-2/5 font-mono disabled:text-zinc-400 disabled:bg-zinc-950/60`}
+ />
+ <div className="flex gap-1.5 flex-1 min-w-0">
+ <div className="relative flex-1 min-w-0">
+ <input
+ aria-label={`Value for ${row.key || 'this entry'}`}
+ type={shown[i] ? 'text' : 'password'}
+ autoComplete="off"
+ value={row.value}
+ onChange={(e) => update(i, { value: e.target.value })}
+ placeholder={row.saved ? '•••••••• saved, leave blank to keep' : 'Secret value'}
+ className={`${inputCls} pr-8 font-mono`}
+ />
+ <button
+ type="button"
+ onClick={() => setShown((s) => ({ ...s, [i]: !s[i] }))}
+ aria-label={shown[i] ? 'Hide value' : 'Show value'}
+ className="absolute right-1.5 top-1/2 -translate-y-1/2 p-1 rounded text-zinc-500 hover:text-zinc-200"
+ >
+ {shown[i] ? <EyeOff size={13} /> : <Eye size={13} />}
+ </button>
+ </div>
+ <button
+ type="button"
+ onClick={() => onChange(rows.filter((_, j) => j !== i))}
+ aria-label={`Remove ${row.key || 'entry'}`}
+ className="p-2 rounded-lg text-zinc-500 hover:text-rose-300 hover:bg-rose-500/10 transition-colors"
+ >
+ <Trash2 size={14} />
+ </button>
+ </div>
+ </div>
+ ))}
+ <button
+ type="button"
+ onClick={() => onChange([...rows, { key: '', value: '', saved: false }])}
+ className="inline-flex items-center gap-1 px-2 py-1 rounded-md text-[11px] font-medium text-sky-300 hover:bg-sky-500/10 transition-colors"
+ >
+ <Plus size={12} />
+ {addLabel}
+ </button>
+ </div>
+ );
+};
+
+const ToolChips: React.FC<{ tools: Array<{ name: string; description?: string }>; max?: number }> = ({ tools, max = 8 }) => {
+ if (tools.length === 0) return <p className="text-[11px] text-zinc-500">Connected, but it didn’t offer any tools.</p>;
+ const extra = tools.length - max;
+ return (
+ <div className="flex flex-wrap gap-1">
+ {tools.slice(0, max).map((t) => (
+ <span
+ key={t.name}
+ title={t.description || t.name}
+ className="inline-flex items-center gap-1 px-2 py-0.5 rounded-md bg-zinc-950/70 border border-zinc-800 text-[11px] text-zinc-300"
+ >
+ <Wrench size={10} className="text-sky-400/80" />
+ {humanizeToolName(t.name)}
+ </span>
+ ))}
+ {extra > 0 && <span className="px-2 py-0.5 text-[11px] text-zinc-500">+{extra} more</span>}
+ </div>
+ );
+};
+
+export const McpServersModal: React.FC<McpServersModalProps> = ({ isOpen, onClose }) => {
+ const [servers, setServers] = useState<McpServer[] | null>(null);
+ const [loadError, setLoadError] = useState<string | null>(null);
+ const [statuses, setStatuses] = useState<Record<string, StoredStatus>>({});
+ const [testing, setTesting] = useState<Record<string, boolean>>({});
+ const [testResults, setTestResults] = useState<Record<string, McpTestResult>>({});
+ const [confirmDelete, setConfirmDelete] = useState<string | null>(null);
+ // Form view: null = list, 'new' = adding, otherwise the id being edited.
+ const [editing, setEditing] = useState<string | null>(null);
+ const [form, setForm] = useState<McpFormState>(emptyMcpForm());
+ const [formError, setFormError] = useState<string | null>(null);
+ const [saving, setSaving] = useState(false);
+
+ const refresh = useCallback(async () => {
+ try {
+ const res = await fetch('/api/mcp/servers');
+ if (!res.ok) throw new Error(await readError(res));
+ setServers(await res.json());
+ setLoadError(null);
+ } catch (err) {
+ setLoadError(err instanceof Error ? err.message : 'Could not reach kwnt.');
+ setServers((prev) => prev ?? []);
+ }
+ }, []);
+
+ useEffect(() => {
+ if (!isOpen) return;
+ setEditing(null);
+ setConfirmDelete(null);
+ setTestResults({});
+ setStatuses(loadStatuses());
+ refresh();
+ }, [isOpen, refresh]);
+
+ useEffect(() => {
+ if (!isOpen) return;
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key !== 'Escape') return;
+ if (editing) setEditing(null);
+ else onClose();
+ };
+ window.addEventListener('keydown', onKey);
+ return () => window.removeEventListener('keydown', onKey);
+ }, [isOpen, editing, onClose]);
+
+ if (!isOpen) return null;
+
+ const setStatus = (id: string, status: StoredStatus | null) => {
+ setStatuses((prev) => {
+ const next = { ...prev };
+ if (status) next[id] = status;
+ else delete next[id];
+ saveStatuses(next);
+ return next;
+ });
+ };
+
+ const runTest = async (id: string) => {
+ setTesting((t) => ({ ...t, [id]: true }));
+ let result: McpTestResult;
+ try {
+ const res = await fetch(`/api/mcp/servers/${id}/test`, { method: 'POST' });
+ result = res.ok ? await res.json() : { ok: false, error: await readError(res) };
+ } catch {
+ result = { ok: false, error: 'Could not reach kwnt.' };
+ }
+ setTesting((t) => ({ ...t, [id]: false }));
+ setTestResults((r) => ({ ...r, [id]: result }));
+ setStatus(id, { ok: result.ok, tools: (result.tools ?? []).map((t) => t.name), error: result.error, at: new Date().toISOString() });
+ playSfx(result.ok ? 'coin' : 'alert');
+ };
+
+ const openForm = (target: 'new' | McpServer, preset?: McpFormState) => {
+ playSfx('click');
+ setFormError(null);
+ if (target === 'new') {
+ setEditing('new');
+ setForm(preset ? { ...preset, env: preset.env.map((r) => ({ ...r })), headers: preset.headers.map((r) => ({ ...r })) } : emptyMcpForm());
+ } else {
+ setEditing(target.id);
+ setForm(serverToForm(target));
+ }
+ };
+
+ const handleSave = async (e: React.FormEvent) => {
+ e.preventDefault();
+ const problem = validateMcpForm(form);
+ if (problem) {
+ setFormError(problem);
+ return;
+ }
+ setSaving(true);
+ setFormError(null);
+ try {
+ const isNew = editing === 'new';
+ const res = await fetch(isNew ? '/api/mcp/servers' : `/api/mcp/servers/${editing}`, {
+ method: isNew ? 'POST' : 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(formToPayload(form)),
+ });
+ if (res.status === 409) {
+ setFormError(`A server named "${form.name.trim()}" already exists.`);
+ return;
+ }
+ if (!res.ok) {
+ setFormError(await readError(res));
+ return;
+ }
+ const saved: McpServer = await res.json();
+ setEditing(null);
+ await refresh();
+ // Config changed, so the old status no longer says anything: test right away.
+ setStatus(saved.id, null);
+ runTest(saved.id);
+ } catch {
+ setFormError('Could not reach kwnt.');
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ const handleDelete = async (server: McpServer) => {
+ playSfx('click');
+ const res = await fetch(`/api/mcp/servers/${server.id}`, { method: 'DELETE' }).catch(() => null);
+ setConfirmDelete(null);
+ if (!res || !res.ok) {
+ setLoadError(res ? await readError(res) : 'Could not reach kwnt.');
+ return;
+ }
+ setStatus(server.id, null);
+ refresh();
+ };
+
+ const toggleEnabled = async (server: McpServer) => {
+ playSfx('click');
+ // Sending the masks back keeps every stored secret.
+ const res = await fetch(`/api/mcp/servers/${server.id}`, {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ ...formToPayload(serverToForm(server)), enabled: !server.enabled }),
+ }).catch(() => null);
+ if (!res || !res.ok) setLoadError(res ? await readError(res) : 'Could not reach kwnt.');
+ refresh();
+ };
+
+ const close = () => {
+ playSfx('click');
+ onClose();
+ };
+
+ const parsed = splitCommandLine(form.commandLine);
+
+ const renderEmpty = () => (
+ <div className="text-center py-6 px-2 space-y-5">
+ <div className="mx-auto w-14 h-14 rounded-2xl bg-sky-500/10 border border-sky-500/20 flex items-center justify-center text-sky-300">
+ <Plug size={26} />
+ </div>
+ <div className="space-y-1.5 max-w-md mx-auto">
+ <h3 className="text-sm font-semibold text-zinc-100">Give your kwants new abilities</h3>
+ <p className="text-xs text-zinc-400 leading-relaxed">
+ MCP servers are small add-ons that hand your kwants tools, like reading files, browsing the web or working with GitHub.
+ Add one here, then choose which kwants may use it. They always ask you before using a tool.
+ </p>
+ </div>
+ <div className="grid grid-cols-1 sm:grid-cols-3 gap-2 text-left">
+ {MCP_PRESETS.map((p) => (
+ <button
+ key={p.id}
+ type="button"
+ onClick={() => openForm('new', p.form)}
+ className="group p-3 rounded-xl border border-zinc-800 bg-zinc-950/60 hover:border-sky-500/40 hover:bg-sky-500/5 text-left transition-all"
+ >
+ <div className="flex items-center gap-1.5 text-xs font-medium text-zinc-200 group-hover:text-sky-200">
+ <Sparkles size={13} className="text-sky-400" />
+ {p.label}
+ </div>
+ <p className="mt-1 text-[11px] text-zinc-500 leading-snug">{p.blurb}</p>
+ </button>
+ ))}
+ </div>
+ <button
+ type="button"
+ onClick={() => openForm('new')}
+ className="inline-flex items-center gap-1.5 px-3.5 py-2 rounded-lg text-xs font-medium text-white bg-sky-600 hover:bg-sky-500 transition-colors shadow-sm"
+ >
+ <Plus size={14} />
+ Add your own server
+ </button>
+ </div>
+ );
+
+ const renderCard = (server: McpServer) => {
+ const status = statuses[server.id];
+ const result = testResults[server.id];
+ const isTesting = !!testing[server.id];
+ const secretCount = Object.keys(server.env).length + Object.keys(server.headers).length;
+ const tools = result?.ok ? result.tools ?? [] : status?.ok ? status.tools.map((name) => ({ name })) : [];
+ return (
+ <li
+ key={server.id}
+ className={`p-3.5 rounded-xl border bg-zinc-950/50 transition-colors ${server.enabled ? 'border-zinc-800' : 'border-zinc-800/60 opacity-75'}`}
+ >
+ <div className="flex items-start gap-3">
+ <div className="w-9 h-9 flex-shrink-0 rounded-lg bg-zinc-900 border border-zinc-800 flex items-center justify-center text-sky-300">
+ {server.transport === 'stdio' ? <Terminal size={16} /> : <Globe size={16} />}
+ </div>
+ <div className="flex-1 min-w-0 space-y-1">
+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1">
+ <span className="text-sm font-semibold text-zinc-100 truncate">{server.name}</span>
+ <StatusPill server={server} status={status} testing={isTesting} />
+ </div>
+ <p className="text-[11px] text-zinc-500">
+ {server.transport === 'stdio' ? 'Runs a command on this machine' : 'Connects to a URL'}
+ {secretCount > 0 && <span> · {secretCount} hidden {secretCount === 1 ? 'secret' : 'secrets'}</span>}
+ </p>
+ <p className="text-[11px] font-mono text-zinc-400 truncate" title={serverTarget(server)}>
+ {serverTarget(server)}
+ </p>
+ </div>
+ </div>
+
+ {tools.length > 0 && (
+ <div className="mt-2.5 pl-12">
+ <ToolChips tools={tools} />
+ </div>
+ )}
+ {result?.ok && tools.length === 0 && (
+ <div className="mt-2.5 pl-12">
+ <ToolChips tools={[]} />
+ </div>
+ )}
+ {result && !result.ok && (
+ <div className="mt-2.5 ml-12 p-2.5 rounded-lg bg-rose-500/5 border border-rose-500/20 text-[11px] text-rose-200 space-y-1">
+ <p>{result.error || 'The server didn’t answer.'}</p>
+ {result.stderr_tail && (
+ <details>
+ <summary className="cursor-pointer text-rose-300/80">What the server printed</summary>
+ <pre className="mt-1 whitespace-pre-wrap break-all font-mono text-[10px] text-zinc-400 max-h-32 overflow-y-auto">{result.stderr_tail}</pre>
+ </details>
+ )}
+ </div>
+ )}
+
+ <div className="mt-3 pt-2.5 border-t border-zinc-800/70 flex flex-wrap items-center justify-between gap-2">
+ {confirmDelete === server.id ? (
+ <div className="flex flex-wrap items-center gap-2 text-[11px] text-zinc-300">
+ <span>Delete {server.name}? Kwants using it lose these tools.</span>
+ <button
+ type="button"
+ onClick={() => setConfirmDelete(null)}
+ className="px-2.5 py-1 rounded-md font-medium text-zinc-300 hover:bg-zinc-800 transition-colors"
+ >
+ Keep it
+ </button>
+ <button
+ type="button"
+ onClick={() => handleDelete(server)}
+ className="px-2.5 py-1 rounded-md font-medium text-white bg-rose-600 hover:bg-rose-500 transition-colors"
+ >
+ Delete
+ </button>
+ </div>
+ ) : (
+ <>
+ <label className="flex items-center gap-2 text-[11px] text-zinc-400 cursor-pointer select-none">
+ <button
+ type="button"
+ role="switch"
+ aria-checked={server.enabled}
+ aria-label={`${server.enabled ? 'Pause' : 'Turn on'} ${server.name}`}
+ onClick={() => toggleEnabled(server)}
+ className={`relative w-8 h-[18px] rounded-full transition-colors ${server.enabled ? 'bg-sky-600' : 'bg-zinc-700'}`}
+ >
+ <span className={`absolute top-0.5 w-3.5 h-3.5 rounded-full bg-white shadow transition-all ${server.enabled ? 'left-[16px]' : 'left-0.5'}`} />
+ </button>
+ {server.enabled ? 'On' : 'Paused'}
+ </label>
+ <div className="flex items-center gap-1">
+ <button
+ type="button"
+ onClick={() => runTest(server.id)}
+ disabled={isTesting}
+ className="inline-flex items-center gap-1 px-2.5 py-1 rounded-md text-[11px] font-medium text-sky-200 bg-sky-500/10 hover:bg-sky-500/20 border border-sky-500/20 transition-colors disabled:opacity-60"
+ >
+ {isTesting ? <Loader2 size={12} className="animate-spin" /> : <Zap size={12} />}
+ Test connection
+ </button>
+ <button
+ type="button"
+ onClick={() => openForm(server)}
+ aria-label={`Edit ${server.name}`}
+ className="p-1.5 rounded-md text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800 transition-colors"
+ >
+ <Pencil size={13} />
+ </button>
+ <button
+ type="button"
+ onClick={() => {
+ playSfx('click');
+ setConfirmDelete(server.id);
+ }}
+ aria-label={`Delete ${server.name}`}
+ className="p-1.5 rounded-md text-zinc-400 hover:text-rose-300 hover:bg-rose-500/10 transition-colors"
+ >
+ <Trash2 size={13} />
+ </button>
+ </div>
+ </>
+ )}
+ </div>
+ </li>
+ );
+ };
+
+ const renderList = () => {
+ if (servers === null) {
+ return (
+ <div className="py-12 flex justify-center text-zinc-500">
+ <Loader2 size={20} className="animate-spin" aria-label="Loading" />
+ </div>
+ );
+ }
+ if (servers.length === 0) return renderEmpty();
+ return (
+ <div className="space-y-3">
+ <div className="flex items-center justify-between gap-2">
+ <p className="text-[11px] text-zinc-500">
+ {servers.length} {servers.length === 1 ? 'server' : 'servers'} · assign them to a kwant from its edit screen
+ </p>
+ <button
+ type="button"
+ onClick={() => openForm('new')}
+ className="flex-shrink-0 inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium text-white bg-sky-600 hover:bg-sky-500 transition-colors shadow-sm whitespace-nowrap"
+ >
+ <Plus size={14} />
+ Add server
+ </button>
+ </div>
+ <ul className="space-y-2.5">{servers.map(renderCard)}</ul>
+ </div>
+ );
+ };
+
+ const renderForm = () => (
+ <form onSubmit={handleSave} className="space-y-5" noValidate>
+ <fieldset>
+ <legend className="text-xs font-medium text-zinc-300 mb-2">
+ <span className="text-sky-400 mr-1.5">1</span>How does it connect?
+ </legend>
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
+ {TRANSPORTS.map((t) => {
+ const active = form.transport === t.id;
+ return (
+ <button
+ key={t.id}
+ type="button"
+ aria-pressed={active}
+ onClick={() => setForm((f) => ({ ...f, transport: t.id }))}
+ className={`flex items-start gap-2.5 p-3 rounded-xl border text-left transition-all ${
+ active ? 'border-sky-500/60 bg-sky-500/10' : 'border-zinc-800 bg-zinc-950/60 hover:border-zinc-700'
+ }`}
+ >
+ <span className={active ? 'text-sky-300' : 'text-zinc-500'}>{t.icon}</span>
+ <span>
+ <span className={`block text-xs font-medium ${active ? 'text-sky-100' : 'text-zinc-200'}`}>{t.title}</span>
+ <span className="block text-[11px] text-zinc-500">{t.blurb}</span>
+ </span>
+ </button>
+ );
+ })}
+ </div>
+ {editing === 'new' && (
+ <div className="mt-2 flex flex-wrap items-center gap-1.5">
+ <span className="text-[11px] text-zinc-500">Or start from an example:</span>
+ {MCP_PRESETS.map((p) => (
+ <button
+ key={p.id}
+ type="button"
+ title={p.blurb}
+ onClick={() => openForm('new', p.form)}
+ className="px-2 py-0.5 rounded-full border border-zinc-800 text-[11px] text-zinc-400 hover:text-sky-200 hover:border-sky-500/40 transition-colors"
+ >
+ {p.label}
+ </button>
+ ))}
+ </div>
+ )}
+ </fieldset>
+
+ <fieldset className="space-y-3">
+ <legend className="text-xs font-medium text-zinc-300 mb-2">
+ <span className="text-sky-400 mr-1.5">2</span>Details
+ </legend>
+ <div>
+ <label htmlFor="mcp-name" className="block text-xs font-medium text-zinc-400 mb-1">Name</label>
+ <input
+ id="mcp-name"
+ value={form.name}
+ onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
+ placeholder="e.g. files, github"
+ className={`${inputCls} font-mono`}
+ />
+ <p className="mt-1 text-[11px] text-zinc-500">
+ Short and simple: letters, numbers, - or _. Kwants see its tools as <span className="font-mono text-zinc-400">{form.name.trim() || 'name'} · tool</span>.
+ </p>
+ </div>
+
+ {form.transport === 'stdio' ? (
+ <>
+ <div>
+ <label htmlFor="mcp-command" className="block text-xs font-medium text-zinc-400 mb-1">Command</label>
+ <input
+ id="mcp-command"
+ value={form.commandLine}
+ onChange={(e) => setForm((f) => ({ ...f, commandLine: e.target.value }))}
+ placeholder="npx -y @modelcontextprotocol/server-filesystem /home/me/projects"
+ spellCheck={false}
+ className={`${inputCls} font-mono`}
+ />
+ <p className="mt-1 text-[11px] text-zinc-500">
+ {parsed.length > 0 ? (
+ <>
+ Runs <span className="font-mono text-zinc-300">{parsed[0]}</span>
+ {parsed.length > 1 ? ` with ${parsed.length - 1} ${parsed.length === 2 ? 'argument' : 'arguments'}` : ''}. Use quotes around paths with spaces.
+ </>
+ ) : (
+ 'Paste it the way the server’s README shows it.'
+ )}
+ </p>
+ </div>
+ <div className="flex items-start gap-2 p-2.5 rounded-lg bg-amber-500/5 border border-amber-500/20 text-[11px] text-amber-200/90">
+ <ShieldAlert size={14} className="flex-shrink-0 mt-px text-amber-400" />
+ <span>This command runs on the kwnt machine with your user’s permissions. Only add servers you trust.</span>
+ </div>
+ <div>
+ <p className="text-xs font-medium text-zinc-400 mb-1">
+ Secrets & settings <span className="text-zinc-600 font-normal">· environment variables, always hidden</span>
+ </p>
+ <SecretRows
+ rows={form.env}
+ onChange={(env) => setForm((f) => ({ ...f, env }))}
+ keyPlaceholder="API_TOKEN"
+ keyLabel="Variable name"
+ addLabel="Add variable"
+ />
+ </div>
+ </>
+ ) : (
+ <>
+ <div>
+ <label htmlFor="mcp-url" className="block text-xs font-medium text-zinc-400 mb-1">Server URL</label>
+ <input
+ id="mcp-url"
+ type="url"
+ value={form.url}
+ onChange={(e) => setForm((f) => ({ ...f, url: e.target.value }))}
+ placeholder="https://example.com/mcp"
+ spellCheck={false}
+ className={`${inputCls} font-mono`}
+ />
+ </div>
+ <div>
+ <p className="text-xs font-medium text-zinc-400 mb-1">
+ Headers <span className="text-zinc-600 font-normal">· e.g. Authorization, always hidden</span>
+ </p>
+ <SecretRows
+ rows={form.headers}
+ onChange={(headers) => setForm((f) => ({ ...f, headers }))}
+ keyPlaceholder="Authorization"
+ keyLabel="Header name"
+ addLabel="Add header"
+ />
+ </div>
+ </>
+ )}
+
+ <details className="group">
+ <summary className="cursor-pointer text-[11px] text-zinc-500 hover:text-zinc-300 select-none">More options</summary>
+ <div className="mt-2 flex flex-wrap items-center gap-4">
+ <label className="flex items-center gap-2 text-[11px] text-zinc-400">
+ Give up after
+ <input
+ type="number"
+ min={1}
+ max={600}
+ value={form.timeout_secs}
+ onChange={(e) => setForm((f) => ({ ...f, timeout_secs: Number(e.target.value) }))}
+ className={`${inputCls} w-20`}
+ />
+ seconds
+ </label>
+ <label className="flex items-center gap-2 text-[11px] text-zinc-400">
+ <input
+ type="checkbox"
+ checked={form.enabled}
+ onChange={(e) => setForm((f) => ({ ...f, enabled: e.target.checked }))}
+ className="accent-sky-500"
+ />
+ Turned on
+ </label>
+ </div>
+ </details>
+ </fieldset>
+
+ {formError && (
+ <p role="alert" className="flex items-center gap-1.5 text-[11px] text-rose-300">
+ <AlertCircle size={13} />
+ {formError}
+ </p>
+ )}
+
+ <div className="flex items-center justify-end gap-2.5 pt-3 border-t border-zinc-800">
+ <button
+ type="button"
+ onClick={() => setEditing(null)}
+ className="px-3.5 py-2 rounded-lg text-xs font-medium text-zinc-300 hover:text-zinc-100 hover:bg-zinc-800 transition-colors"
+ >
+ Cancel
+ </button>
+ <button
+ type="submit"
+ disabled={saving}
+ className="inline-flex items-center gap-1.5 px-4 py-2 rounded-lg text-xs font-medium text-white bg-sky-600 hover:bg-sky-500 transition-colors shadow-sm disabled:opacity-60"
+ >
+ {saving && <Loader2 size={13} className="animate-spin" />}
+ {editing === 'new' ? 'Add & test' : 'Save & test'}
+ </button>
+ </div>
+ </form>
+ );
+
+ return (
+ <div className="fixed inset-0 z-50 bg-black/70 backdrop-blur-sm flex items-center justify-center p-2 sm:p-4" onMouseDown={(e) => e.target === e.currentTarget && close()}>
+ <div
+ role="dialog"
+ aria-modal="true"
+ aria-labelledby="mcp-title"
+ className="bg-zinc-900 border border-zinc-800 rounded-2xl max-w-2xl w-full max-h-[92vh] overflow-y-auto p-4 sm:p-6 text-zinc-100 shadow-2xl space-y-5"
+ >
+ <div className="flex items-center justify-between gap-3 border-b border-zinc-800 pb-4">
+ <div className="flex items-center gap-2.5 min-w-0">
+ {editing ? (
+ <button
+ type="button"
+ onClick={() => setEditing(null)}
+ aria-label="Back to servers"
+ className="w-8 h-8 flex-shrink-0 rounded-lg bg-zinc-800/60 border border-zinc-700/60 flex items-center justify-center text-zinc-300 hover:text-zinc-100"
+ >
+ <ChevronLeft size={17} />
+ </button>
+ ) : (
+ <div className="w-8 h-8 flex-shrink-0 rounded-lg bg-sky-500/10 border border-sky-500/20 flex items-center justify-center text-sky-400">
+ <Plug size={16} />
+ </div>
+ )}
+ <div className="min-w-0">
+ <h2 id="mcp-title" className="text-sm font-semibold text-zinc-100 truncate">
+ {editing === 'new' ? 'Add a tool server' : editing ? `Edit ${form.name || 'server'}` : 'Tools for your kwants'}
+ </h2>
+ <p className="text-xs text-zinc-400 truncate">
+ {editing === 'new'
+ ? 'Pick how it connects, then fill in the details'
+ : editing
+ ? 'Saved secrets stay hidden and are kept unless you change them'
+ : 'MCP servers your kwants can use, with your approval'}
+ </p>
+ </div>
+ </div>
+ <button
+ type="button"
+ onClick={close}
+ aria-label="Close"
+ className="p-1.5 rounded-lg text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800 transition-colors"
+ >
+ <X size={18} />
+ </button>
+ </div>
+
+ {loadError && !editing && (
+ <p role="alert" className="flex items-center gap-1.5 px-3 py-2 rounded-lg bg-rose-500/5 border border-rose-500/20 text-[11px] text-rose-300">
+ <AlertCircle size={13} />
+ {loadError}
+ </p>
+ )}
+
+ {editing ? renderForm() : renderList()}
+ </div>
+ </div>
+ );
+};
diff --git a/frontend/src/components/ModernApprovalCard.tsx b/frontend/src/components/ModernApprovalCard.tsx
index e8f603f3..de0bad7f 100644
--- a/frontend/src/components/ModernApprovalCard.tsx
+++ b/frontend/src/components/ModernApprovalCard.tsx
@@ -1,6 +1,7 @@
import React from 'react';
-import { ShieldAlert, Check, CheckCheck, X } from 'lucide-react';
+import { ShieldAlert, Check, CheckCheck, X, Plug } from 'lucide-react';
import { playSfx } from '../audio/chiptune';
+import { formatArgs, humanizeToolName, parseMcpToolName } from '../mcp';
export interface PendingApproval {
id: string;
@@ -13,6 +14,19 @@ interface ModernApprovalCardProps {
onResolve: (id: string, decision: 'allow_once' | 'always_allow' | 'deny') => void;
}
+/** Server/tool/arguments of an MCP approval, or null for other tools. */
+const mcpView = (approval: PendingApproval) => {
+ const d = approval.details ?? {};
+ const fromName = parseMcpToolName(approval.tool_name);
+ if (d.source !== 'mcp' && !fromName) return null;
+ return {
+ server: typeof d.server === 'string' ? d.server : fromName?.server ?? '',
+ tool: typeof d.tool === 'string' ? d.tool : fromName?.tool ?? approval.tool_name,
+ kwant: typeof d.kwant_name === 'string' ? d.kwant_name : null,
+ args: formatArgs(d.arguments),
+ };
+};
+
export const ModernApprovalCard: React.FC<ModernApprovalCardProps> = ({
approval,
onResolve,
@@ -21,6 +35,7 @@ export const ModernApprovalCard: React.FC<ModernApprovalCardProps> = ({
playSfx('click');
onResolve(approval.id, decision);
};
+ const mcp = mcpView(approval);
return (
<div className="my-3 border border-amber-500/30 bg-amber-950/20 rounded-xl p-4 text-zinc-100 max-w-2xl shadow-lg backdrop-blur-sm">
@@ -29,16 +44,41 @@ export const ModernApprovalCard: React.FC<ModernApprovalCardProps> = ({
<span>Action Approval Required</span>
</div>
- <div className="bg-zinc-900/90 rounded-lg p-3 border border-zinc-800 text-xs font-mono space-y-1 mb-3">
- <div className="text-zinc-400">
- <span className="text-sky-400 font-semibold">Tool:</span> {approval.tool_name}
+ {mcp ? (
+ <div className="bg-zinc-900/90 rounded-lg p-3 border border-zinc-800 text-xs space-y-2 mb-3">
+ <p className="text-zinc-300">
+ {mcp.kwant ? <span className="font-medium text-zinc-100">{mcp.kwant}</span> : 'A kwant'} wants to use{' '}
+ <span className="font-medium text-sky-200">{humanizeToolName(mcp.tool)}</span>
+ {mcp.server && (
+ <>
+ {' '}from <span className="inline-flex items-center gap-1 font-medium text-zinc-100"><Plug size={11} className="text-sky-400" />{mcp.server}</span>
+ </>
+ )}
+ .
+ </p>
+ <p className="font-mono text-[11px] text-zinc-500">
+ {mcp.server} · {mcp.tool}
+ </p>
+ {mcp.args ? (
+ <pre className="font-mono text-[11px] text-zinc-300 bg-zinc-950/70 border border-zinc-800 rounded-md p-2 whitespace-pre-wrap break-all max-h-48 overflow-y-auto">
+ {mcp.args}
+ </pre>
+ ) : (
+ <p className="text-[11px] text-zinc-500">No arguments.</p>
+ )}
</div>
- <div className="text-zinc-300 break-all overflow-x-auto max-h-36 py-1">
- {JSON.stringify(approval.details, null, 2)}
+ ) : (
+ <div className="bg-zinc-900/90 rounded-lg p-3 border border-zinc-800 text-xs font-mono space-y-1 mb-3">
+ <div className="text-zinc-400">
+ <span className="text-sky-400 font-semibold">Tool:</span> {approval.tool_name}
+ </div>
+ <div className="text-zinc-300 break-all overflow-x-auto max-h-36 py-1">
+ {JSON.stringify(approval.details, null, 2)}
+ </div>
</div>
- </div>
+ )}
- <div className="flex items-center justify-end gap-2">
+ <div className="flex flex-wrap items-center justify-end gap-2">
<button
onClick={() => handleDecision('deny')}
className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium text-zinc-300 bg-zinc-800 hover:bg-zinc-700 transition-colors"
@@ -57,6 +97,7 @@ export const ModernApprovalCard: React.FC<ModernApprovalCardProps> = ({
<button
onClick={() => handleDecision('always_allow')}
+ title={mcp ? 'Allow this tool for this kwant until kwnt restarts' : undefined}
className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium text-white bg-sky-600 hover:bg-sky-500 transition-colors shadow-sm"
>
<CheckCheck size={14} />
diff --git a/frontend/src/components/NewAgentModal.tsx b/frontend/src/components/NewAgentModal.tsx
index 0d9909fd..b00bc096 100644
--- a/frontend/src/components/NewAgentModal.tsx
+++ b/frontend/src/components/NewAgentModal.tsx
@@ -3,6 +3,7 @@ import { X, Sparkles, Pencil } from 'lucide-react';
import { ModernAvatar, AVATAR_STYLES } from './ModernAvatar';
import { AGENT_PRESETS, AgentPreset, PRESET_GROUPS, PresetGroup, uniqueAgentName } from '../agentPresets';
import { playSfx } from '../audio/chiptune';
+import { KwantToolsPicker } from './KwantToolsPicker';
export interface AgentFormData {
name: string;
@@ -11,6 +12,8 @@ export interface AgentFormData {
soul?: string;
avatar_sprite: string;
preferred_model: string;
+ /** MCP servers this kwant may use; undefined when they weren't loaded. */
+ mcp_server_ids?: string[];
}
const MODEL_OPTIONS = [
@@ -30,6 +33,10 @@ interface NewAgentModalProps {
takenNames?: string[];
/** When creating from a team, the team the new agent will join. */
joinTeamName?: string;
+ /** The agent being edited, to load its tool servers. */
+ kwantId?: string;
+ /** Opens the MCP servers screen. */
+ onManageServers?: () => void;
/** Resolves to an error message when saving failed. */
onSubmit: (data: AgentFormData) => Promise<string | void> | void;
}
@@ -40,6 +47,8 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({
initial,
takenNames = [],
joinTeamName,
+ kwantId,
+ onManageServers,
onSubmit,
}) => {
const [name, setName] = useState('');
@@ -52,6 +61,7 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({
const [error, setError] = useState<string | null>(null);
const [presetId, setPresetId] = useState<string | null>(null);
const [presetGroup, setPresetGroup] = useState<PresetGroup>('tech');
+ const [mcpIds, setMcpIds] = useState<string[] | undefined>(undefined);
const isEdit = !!initial;
useEffect(() => {
@@ -65,7 +75,14 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({
setSubmitting(false);
setError(null);
setPresetId(null);
- }, [isOpen, initial]);
+ setMcpIds(kwantId ? undefined : []);
+ if (kwantId) {
+ fetch(`/api/kwants/${kwantId}/mcp-servers`)
+ .then((r) => (r.ok ? r.json() : { server_ids: [] }))
+ .then((d) => setMcpIds(d.server_ids ?? []))
+ .catch(() => setMcpIds([]));
+ }
+ }, [isOpen, initial, kwantId]);
const applyPreset = (preset: AgentPreset | null) => {
playSfx('click');
@@ -100,6 +117,7 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({
soul: soul.trim(),
avatar_sprite: roleStyle,
preferred_model: model,
+ mcp_server_ids: mcpIds,
});
setSubmitting(false);
@@ -253,6 +271,10 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({
</select>
</div>
+ {mcpIds !== undefined && (
+ <KwantToolsPicker model={model} selected={mcpIds} onChange={setMcpIds} onManageServers={onManageServers} />
+ )}
+
<div>
<label className="block text-xs font-medium text-zinc-400 mb-1">Persona & Instructions</label>
<textarea
diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsx
index e0775e4e..f9ec12a9 100644
--- a/frontend/src/components/SettingsModal.tsx
+++ b/frontend/src/components/SettingsModal.tsx
@@ -1,5 +1,5 @@
import React, { useState, useEffect } from 'react';
-import { Cpu, Key, Globe, X, Sparkles, Check } from 'lucide-react';
+import { Cpu, Key, Globe, X, Sparkles, Check, Plug, ChevronRight } from 'lucide-react';
import { playSfx } from '../audio/chiptune';
interface SettingsData {
@@ -18,9 +18,10 @@ interface SettingsData {
interface SettingsModalProps {
isOpen: boolean;
onClose: () => void;
+ onOpenTools?: () => void;
}
-export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose }) => {
+export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, onOpenTools }) => {
const [settings, setSettings] = useState<SettingsData | null>(null);
const [anthropicKey, setAnthropicKey] = useState('');
const [xaiKey, setXaiKey] = useState('');
@@ -77,7 +78,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose })
return (
<div className="fixed inset-0 z-50 bg-black/70 backdrop-blur-sm flex items-center justify-center p-4 select-none">
- <div className="bg-zinc-900 border border-zinc-800 rounded-2xl max-w-lg w-full p-6 text-zinc-100 shadow-2xl space-y-6">
+ <div className="bg-zinc-900 border border-zinc-800 rounded-2xl max-w-lg w-full max-h-[92vh] overflow-y-auto p-6 text-zinc-100 shadow-2xl space-y-6">
{/* Header */}
<div className="flex items-center justify-between border-b border-zinc-800 pb-4">
<div className="flex items-center gap-2.5">
@@ -144,6 +145,26 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose })
</div>
</div>
+ {onOpenTools && (
+ <button
+ type="button"
+ onClick={() => {
+ playSfx('click');
+ onOpenTools();
+ }}
+ className="w-full flex items-center gap-3 p-3 rounded-xl border border-zinc-800 bg-zinc-950/60 hover:border-sky-500/40 text-left transition-colors group"
+ >
+ <span className="w-8 h-8 rounded-lg bg-sky-500/10 border border-sky-500/20 flex items-center justify-center text-sky-400">
+ <Plug size={15} />
+ </span>
+ <span className="flex-1">
+ <span className="block text-xs font-medium text-zinc-200">Tools (MCP servers)</span>
+ <span className="block text-[11px] text-zinc-500">Give kwants abilities like files, web pages or GitHub</span>
+ </span>
+ <ChevronRight size={15} className="text-zinc-500 group-hover:text-sky-300" />
+ </button>
+ )}
+
{/* Cloud API Keys Form */}
<form onSubmit={handleSave} className="space-y-4">
<div className="flex items-center gap-2 text-xs font-medium text-zinc-300">
diff --git a/frontend/src/components/ToolCallsList.tsx b/frontend/src/components/ToolCallsList.tsx
new file mode 100644
index 00000000..25490b33
--- /dev/null
+++ b/frontend/src/components/ToolCallsList.tsx
@@ -0,0 +1,74 @@
+import React from 'react';
+import { CheckCircle2, AlertCircle, Ban, ShieldCheck, ChevronRight, Wrench } from 'lucide-react';
+import { RecordedToolCall, formatArgs, humanizeToolName, parseToolCalls } from '../mcp';
+
+const STATUS: Record<string, { icon: React.ReactNode; label: string; cls: string }> = {
+ ok: { icon: <CheckCircle2 size={12} />, label: 'Done', cls: 'text-emerald-300' },
+ allowed: { icon: <ShieldCheck size={12} />, label: 'Allowed', cls: 'text-emerald-300' },
+ error: { icon: <AlertCircle size={12} />, label: 'Failed', cls: 'text-rose-300' },
+ denied: { icon: <Ban size={12} />, label: 'Denied', cls: 'text-zinc-400' },
+};
+
+const ToolCallRow: React.FC<{ call: RecordedToolCall }> = ({ call }) => {
+ const status = STATUS[call.status ?? ''] ?? { icon: <Wrench size={12} />, label: call.status ?? '', cls: 'text-zinc-400' };
+ const args = formatArgs(call.arguments);
+ const hasDetail = !!args || !!call.result;
+ const head = (
+ <>
+ <span className={`flex-shrink-0 ${status.cls}`} title={status.label}>
+ {status.icon}
+ </span>
+ <span className="text-zinc-200 font-medium truncate">{humanizeToolName(call.tool ?? call.name)}</span>
+ {call.server && <span className="text-zinc-500 truncate">· {call.server}</span>}
+ <span className="ml-auto flex items-center gap-2 flex-shrink-0 text-[10px] text-zinc-500">
+ <span className={status.cls}>{status.label}</span>
+ {typeof call.duration_ms === 'number' && <span className="font-mono">{call.duration_ms} ms</span>}
+ {hasDetail && <ChevronRight size={12} className="transition-transform group-open:rotate-90" />}
+ </span>
+ </>
+ );
+
+ if (!hasDetail) return <li className="flex items-center gap-2 px-3 py-1.5 text-[11px]">{head}</li>;
+ return (
+ <li>
+ <details className="group">
+ <summary className="flex items-center gap-2 px-3 py-1.5 text-[11px] cursor-pointer list-none hover:bg-zinc-900/60 [&::-webkit-details-marker]:hidden">
+ {head}
+ </summary>
+ <div className="px-3 pb-2.5 space-y-1.5">
+ {args && (
+ <div>
+ <p className="text-[10px] uppercase tracking-wide text-zinc-500 mb-0.5">Input</p>
+ <pre className="font-mono text-[11px] text-zinc-300 bg-zinc-950/80 border border-zinc-800 rounded-md p-2 whitespace-pre-wrap break-all max-h-40 overflow-y-auto">{args}</pre>
+ </div>
+ )}
+ {call.result && (
+ <div>
+ <p className="text-[10px] uppercase tracking-wide text-zinc-500 mb-0.5">Result</p>
+ <pre className="font-mono text-[11px] text-zinc-300 bg-zinc-950/80 border border-zinc-800 rounded-md p-2 whitespace-pre-wrap break-all max-h-40 overflow-y-auto">{call.result}</pre>
+ </div>
+ )}
+ </div>
+ </details>
+ </li>
+ );
+};
+
+/** The MCP tools a reply used, recorded in the message's `tool_calls`. */
+export const ToolCallsList: React.FC<{ raw: unknown }> = ({ raw }) => {
+ const calls = parseToolCalls(raw);
+ if (calls.length === 0) return null;
+ return (
+ <div className="mt-2 w-full max-w-2xl rounded-xl border border-zinc-800 bg-zinc-950/50 overflow-hidden">
+ <p className="flex items-center gap-1.5 px-3 pt-2 pb-1 text-[10px] font-medium uppercase tracking-wide text-zinc-500">
+ <Wrench size={11} className="text-sky-400/80" />
+ Used {calls.length} {calls.length === 1 ? 'tool' : 'tools'}
+ </p>
+ <ul className="divide-y divide-zinc-800/70">
+ {calls.map((call, i) => (
+ <ToolCallRow key={call.id ?? i} call={call} />
+ ))}
+ </ul>
+ </div>
+ );
+};
diff --git a/frontend/src/mcp.ts b/frontend/src/mcp.ts
new file mode 100644
index 00000000..e54f3939
--- /dev/null
+++ b/frontend/src/mcp.ts
@@ -0,0 +1,329 @@
+// MCP server helpers shared by the servers screen, the per-kwant picker and chat.
+// Contract: docs/mcp-api.md
+
+export type McpTransport = 'stdio' | 'http';
+
+export interface McpServer {
+ id: string;
+ name: string;
+ transport: McpTransport;
+ command: string | null;
+ args: string[];
+ url: string | null;
+ env: Record<string, string>;
+ headers: Record<string, string>;
+ enabled: boolean;
+ timeout_secs: number;
+ created_at: string | null;
+}
+
+export interface McpTool {
+ name: string;
+ description?: string;
+ input_schema?: unknown;
+}
+
+export interface McpTestResult {
+ ok: boolean;
+ server_info?: { name?: string; version?: string };
+ duration_ms?: number;
+ tools?: McpTool[];
+ error?: string;
+ stderr_tail?: string;
+}
+
+/** What the API returns in place of every stored secret value. */
+export const SECRET_MASK = '********';
+
+export interface SecretRow {
+ key: string;
+ value: string;
+ /** Already stored on the server: a blank value keeps it. */
+ saved: boolean;
+}
+
+export interface McpFormState {
+ name: string;
+ transport: McpTransport;
+ /** Command and arguments as one line, the way READMEs show them. */
+ commandLine: string;
+ url: string;
+ env: SecretRow[];
+ headers: SecretRow[];
+ enabled: boolean;
+ timeout_secs: number;
+}
+
+export const emptyMcpForm = (transport: McpTransport = 'stdio'): McpFormState => ({
+ name: '',
+ transport,
+ commandLine: '',
+ url: '',
+ env: [],
+ headers: [],
+ enabled: true,
+ timeout_secs: 30,
+});
+
+export interface McpPreset {
+ id: string;
+ label: string;
+ blurb: string;
+ form: McpFormState;
+}
+
+/** Ready-made examples offered on the empty screen and in the form. */
+export const MCP_PRESETS: McpPreset[] = [
+ {
+ id: 'files',
+ label: 'Files in a folder',
+ blurb: 'Read and write files in one folder you choose. Needs Node.js.',
+ form: {
+ ...emptyMcpForm('stdio'),
+ name: 'files',
+ commandLine: 'npx -y @modelcontextprotocol/server-filesystem /home/me/projects',
+ },
+ },
+ {
+ id: 'fetch',
+ label: 'Read web pages',
+ blurb: 'Fetch a URL and turn the page into readable text. Needs uv.',
+ form: { ...emptyMcpForm('stdio'), name: 'fetch', commandLine: 'uvx mcp-server-fetch' },
+ },
+ {
+ id: 'github',
+ label: 'GitHub',
+ blurb: 'Issues, pull requests and code search. Needs a GitHub token.',
+ form: {
+ ...emptyMcpForm('stdio'),
+ name: 'github',
+ commandLine: 'npx -y @modelcontextprotocol/server-github',
+ env: [{ key: 'GITHUB_PERSONAL_ACCESS_TOKEN', value: '', saved: false }],
+ },
+ },
+];
+
+/** Splits a command line into words, honouring '…' and "…" quotes and backslash escapes. */
+export const splitCommandLine = (line: string): string[] => {
+ const words: string[] = [];
+ let current = '';
+ let inWord = false;
+ let quote: '"' | "'" | null = null;
+ for (let i = 0; i < line.length; i++) {
+ const ch = line[i];
+ if (quote) {
+ if (ch === quote) quote = null;
+ else if (ch === '\\' && quote === '"' && i + 1 < line.length) current += line[++i];
+ else current += ch;
+ } else if (ch === '"' || ch === "'") {
+ quote = ch;
+ inWord = true;
+ } else if (ch === '\\' && i + 1 < line.length) {
+ current += line[++i];
+ inWord = true;
+ } else if (/\s/.test(ch)) {
+ if (inWord) words.push(current);
+ current = '';
+ inWord = false;
+ } else {
+ current += ch;
+ inWord = true;
+ }
+ }
+ if (inWord) words.push(current);
+ return words;
+};
+
+const quoteWord = (word: string) =>
+ word === '' || /[\s'"\\]/.test(word) ? `"${word.replace(/(["\\])/g, '\\$1')}"` : word;
+
+/** Inverse of splitCommandLine. */
+export const joinCommandLine = (words: string[]): string => words.map(quoteWord).join(' ');
+
+const NAME_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,47}$/;
+const ENV_KEY_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
+
+/** Turns any label into a valid server name ("My Files!" → "my-files"). */
+export const toServerName = (label: string): string =>
+ label
+ .trim()
+ .toLowerCase()
+ .replace(/[^a-z0-9_-]+/g, '-')
+ .replace(/_{2,}/g, '_')
+ .replace(/^[-_]+|[-_]+$/g, '')
+ .slice(0, 48);
+
+/** Returns a friendly message for the first problem in the form, or null when it can be saved. */
+export const validateMcpForm = (form: McpFormState): string | null => {
+ const name = form.name.trim();
+ if (!name) return 'Give the server a short name.';
+ if (!NAME_RE.test(name) || name.includes('__'))
+ return 'Use letters, numbers, - or _ for the name (no spaces, up to 48 characters).';
+ if (name.toLowerCase() === 'kwnt') return '"kwnt" is reserved, pick another name.';
+ if (form.transport === 'stdio') {
+ if (splitCommandLine(form.commandLine).length === 0) return 'Add the command that starts the server.';
+ const bad = form.env.find((r) => r.key.trim() && !ENV_KEY_RE.test(r.key.trim()));
+ if (bad) return `"${bad.key}" isn't a valid variable name (letters, numbers and _ only).`;
+ } else {
+ if (!/^https?:\/\/\S+$/.test(form.url.trim())) return 'The URL should start with http:// or https://.';
+ }
+ if (!Number.isInteger(form.timeout_secs) || form.timeout_secs < 1 || form.timeout_secs > 600)
+ return 'Timeout should be between 1 and 600 seconds.';
+ return null;
+};
+
+const rowsToMap = (rows: SecretRow[]): Record<string, string> => {
+ const out: Record<string, string> = {};
+ for (const row of rows) {
+ const key = row.key.trim();
+ if (!key) continue;
+ // A saved secret left blank is sent back as the mask, which keeps the stored value.
+ out[key] = row.saved && row.value === '' ? SECRET_MASK : row.value;
+ }
+ return out;
+};
+
+/** Request body for POST/PUT /api/mcp/servers. Rows that were removed are left out, which deletes them. */
+export const formToPayload = (form: McpFormState) => {
+ const base = { name: form.name.trim(), transport: form.transport, enabled: form.enabled, timeout_secs: form.timeout_secs };
+ if (form.transport === 'stdio') {
+ const [command, ...args] = splitCommandLine(form.commandLine);
+ return { ...base, command, args, url: null, env: rowsToMap(form.env), headers: {} };
+ }
+ return { ...base, command: null, args: [], url: form.url.trim(), env: {}, headers: rowsToMap(form.headers) };
+};
+
+const mapToRows = (map: Record<string, string> | null | undefined): SecretRow[] =>
+ Object.keys(map ?? {}).map((key) => ({ key, value: '', saved: true }));
+
+export const serverToForm = (server: McpServer): McpFormState => ({
+ name: server.name,
+ transport: server.transport,
+ commandLine: server.command ? joinCommandLine([server.command, ...(server.args ?? [])]) : '',
+ url: server.url ?? '',
+ env: mapToRows(server.env),
+ headers: mapToRows(server.headers),
+ enabled: server.enabled,
+ timeout_secs: server.timeout_secs || 30,
+});
+
+/** One-line summary of where a server lives, for cards. */
+export const serverTarget = (server: McpServer): string =>
+ server.transport === 'stdio'
+ ? joinCommandLine([server.command ?? '', ...(server.args ?? [])])
+ : server.url ?? '';
+
+/** Splits `mcp__<server>__<tool>`; null for anything else. */
+export const parseMcpToolName = (name: string): { server: string; tool: string } | null => {
+ const m = /^mcp__(.+?)__(.+)$/.exec(name ?? '');
+ return m ? { server: m[1], tool: m[2] } : null;
+};
+
+/** `read_file` → `read file`, for display. */
+export const humanizeToolName = (tool: string): string => tool.replace(/[_-]+/g, ' ').trim();
+
+export interface RecordedToolCall {
+ id?: string;
+ name: string;
+ server?: string;
+ tool?: string;
+ arguments?: unknown;
+ status?: 'ok' | 'error' | 'denied' | 'allowed' | string;
+ result?: string;
+ duration_ms?: number;
+}
+
+/** Reads a message's `tool_calls` (a JSON string from the API, or already parsed). */
+export const parseToolCalls = (raw: unknown): RecordedToolCall[] => {
+ let value = raw;
+ if (typeof raw === 'string') {
+ if (!raw.trim()) return [];
+ try {
+ value = JSON.parse(raw);
+ } catch {
+ return [];
+ }
+ }
+ if (!Array.isArray(value)) return [];
+ return value
+ .filter((c): c is RecordedToolCall => !!c && typeof c === 'object' && typeof (c as RecordedToolCall).name === 'string')
+ .map((c) => {
+ const parsed = parseMcpToolName(c.name);
+ return { ...c, server: c.server ?? parsed?.server, tool: c.tool ?? parsed?.tool ?? c.name };
+ });
+};
+
+/** Pretty-prints tool arguments; strings that hold JSON are unpacked first. */
+export const formatArgs = (args: unknown): string => {
+ if (args === undefined || args === null) return '';
+ let value = args;
+ if (typeof args === 'string') {
+ try {
+ value = JSON.parse(args);
+ } catch {
+ return args;
+ }
+ }
+ if (value && typeof value === 'object' && Object.keys(value).length === 0) return '';
+ return JSON.stringify(value, null, 2);
+};
+
+export interface EngineKeys {
+ anthropic: boolean;
+ openai: boolean;
+ xai: boolean;
+}
+
+/**
+ * Whether a kwant with this engine can use MCP tools, mirroring how kwnt picks a driver
+ * (an API key in Settings wins over the local CLI). `note` is shown instead of pretending.
+ */
+export const mcpSupportFor = (preferredModel: string, keys: EngineKeys): { supported: boolean; note: string | null } => {
+ const model = (preferredModel || 'auto').toLowerCase();
+ if (model === 'local_ollama') return { supported: true, note: null };
+ if (model.includes('claude')) {
+ return keys.anthropic
+ ? { supported: false, note: 'With an Anthropic API key set, Claude runs through the Anthropic API, which can’t use MCP tools yet. Remove the key to use the Claude Code CLI instead.' }
+ : { supported: true, note: null };
+ }
+ if (model.includes('grok')) {
+ return keys.xai
+ ? { supported: true, note: null }
+ : { supported: false, note: 'The Grok CLI can’t use MCP tools yet. Add an xAI API key in Settings to use them with Grok.' };
+ }
+ if (model.includes('codex') || model.includes('gpt') || model.includes('openai')) {
+ return keys.openai
+ ? { supported: true, note: null }
+ : { supported: false, note: 'The Codex CLI can’t use MCP tools yet. Add an OpenAI API key in Settings to use them with this engine.' };
+ }
+ return {
+ supported: true,
+ note: 'Laya picks the engine for each message. Tools work with Claude Code, Ollama and API keys, but not through the Codex or Grok CLIs.',
+ };
+};
+
+/** Last test result per server, kept in the browser so cards can show a status. */
+const STATUS_KEY = 'kwnt.mcp.lastTest';
+
+export interface StoredStatus {
+ ok: boolean;
+ tools: string[];
+ error?: string;
+ at: string;
+}
+
+export const loadStatuses = (): Record<string, StoredStatus> => {
+ try {
+ return JSON.parse(localStorage.getItem(STATUS_KEY) || '{}') ?? {};
+ } catch {
+ return {};
+ }
+};
+
+export const saveStatuses = (statuses: Record<string, StoredStatus>) => {
+ try {
+ localStorage.setItem(STATUS_KEY, JSON.stringify(statuses));
+ } catch {
+ // storage full or blocked: status is a nicety
+ }
+};
diff --git a/frontend/tests/mcp.test.mjs b/frontend/tests/mcp.test.mjs
new file mode 100644
index 00000000..8e20ce13
--- /dev/null
+++ b/frontend/tests/mcp.test.mjs
@@ -0,0 +1,152 @@
+import assert from 'node:assert/strict';
+import { readFile } from 'node:fs/promises';
+import test from 'node:test';
+import ts from 'typescript';
+
+const source = await readFile(new URL('../src/mcp.ts', import.meta.url), 'utf8');
+const { outputText } = ts.transpileModule(source, {
+ compilerOptions: { module: ts.ModuleKind.ESNext },
+});
+const mcp = await import(`data:text/javascript;base64,${Buffer.from(outputText).toString('base64')}`);
+const {
+ MCP_PRESETS,
+ SECRET_MASK,
+ emptyMcpForm,
+ formToPayload,
+ serverToForm,
+ splitCommandLine,
+ joinCommandLine,
+ validateMcpForm,
+ toServerName,
+ parseMcpToolName,
+ parseToolCalls,
+ formatArgs,
+ mcpSupportFor,
+} = mcp;
+
+test('splits command lines like a README shows them', () => {
+ assert.deepEqual(splitCommandLine('npx -y @scope/server /home/me'), ['npx', '-y', '@scope/server', '/home/me']);
+ assert.deepEqual(splitCommandLine(`run "my folder" 'it''s' a\\ b ""`), ['run', 'my folder', 'its', 'a b', '']);
+ assert.deepEqual(splitCommandLine(' '), []);
+});
+
+test('joining and splitting round-trips awkward arguments', () => {
+ const words = ['kwnt', 'mcp-echo-server', 'with space', 'quo"te', 'back\\slash', ''];
+ assert.deepEqual(splitCommandLine(joinCommandLine(words)), words);
+ assert.equal(joinCommandLine(['npx', '-y', 'pkg']), 'npx -y pkg');
+});
+
+test('validates names, command, URL and timeout with friendly messages', () => {
+ const ok = { ...emptyMcpForm(), name: 'echo', commandLine: 'kwnt mcp-echo-server' };
+ assert.equal(validateMcpForm(ok), null);
+ assert.match(validateMcpForm({ ...ok, name: '' }), /name/);
+ assert.match(validateMcpForm({ ...ok, name: 'has space' }), /letters/);
+ assert.match(validateMcpForm({ ...ok, name: 'a__b' }), /letters/);
+ assert.match(validateMcpForm({ ...ok, name: 'KWNT' }), /reserved/);
+ assert.match(validateMcpForm({ ...ok, commandLine: ' ' }), /command/);
+ assert.match(validateMcpForm({ ...ok, env: [{ key: '1BAD', value: 'x', saved: false }] }), /variable/);
+ const http = { ...emptyMcpForm('http'), name: 'remote', url: 'ftp://x' };
+ assert.match(validateMcpForm(http), /http/);
+ assert.equal(validateMcpForm({ ...http, url: 'https://example.com/mcp' }), null);
+ assert.match(validateMcpForm({ ...ok, timeout_secs: 0 }), /Timeout/);
+ assert.equal(toServerName(' My Files! '), 'my-files');
+});
+
+test('stdio payload splits the command and keeps blank saved secrets as the mask', () => {
+ const payload = formToPayload({
+ ...emptyMcpForm(),
+ name: ' gh ',
+ commandLine: 'npx -y "@x/server github"',
+ env: [
+ { key: 'KEEP', value: '', saved: true },
+ { key: 'CHANGE', value: 'new', saved: true },
+ { key: 'NEW', value: 'v', saved: false },
+ { key: ' ', value: 'ignored', saved: false },
+ ],
+ });
+ assert.equal(payload.name, 'gh');
+ assert.equal(payload.command, 'npx');
+ assert.deepEqual(payload.args, ['-y', '@x/server github']);
+ assert.equal(payload.url, null);
+ assert.deepEqual(payload.env, { KEEP: SECRET_MASK, CHANGE: 'new', NEW: 'v' });
+ assert.deepEqual(payload.headers, {});
+});
+
+test('http payload sends only the URL and headers', () => {
+ const payload = formToPayload({
+ ...emptyMcpForm('http'),
+ name: 'remote',
+ commandLine: 'left over',
+ url: ' https://example.com/mcp ',
+ env: [{ key: 'X', value: 'y', saved: false }],
+ headers: [{ key: 'Authorization', value: '', saved: true }],
+ });
+ assert.equal(payload.command, null);
+ assert.deepEqual(payload.args, []);
+ assert.equal(payload.url, 'https://example.com/mcp');
+ assert.deepEqual(payload.env, {});
+ assert.deepEqual(payload.headers, { Authorization: SECRET_MASK });
+});
+
+test('editing a server never puts the mask in an input, and saving unchanged keeps every secret', () => {
+ const server = {
+ id: '1', name: 'gh', transport: 'stdio', command: 'npx', args: ['-y', 'a b'], url: null,
+ env: { TOKEN: SECRET_MASK }, headers: {}, enabled: false, timeout_secs: 12, created_at: null,
+ };
+ const form = serverToForm(server);
+ assert.equal(form.commandLine, 'npx -y "a b"');
+ assert.deepEqual(form.env, [{ key: 'TOKEN', value: '', saved: true }]);
+ assert.equal(form.enabled, false);
+ assert.equal(form.timeout_secs, 12);
+ const payload = formToPayload(form);
+ assert.deepEqual(payload.env, { TOKEN: SECRET_MASK });
+ assert.deepEqual([payload.command, ...payload.args], ['npx', '-y', 'a b']);
+});
+
+test('presets are valid forms with distinct ids', () => {
+ assert.ok(MCP_PRESETS.length >= 2);
+ assert.equal(new Set(MCP_PRESETS.map((p) => p.id)).size, MCP_PRESETS.length);
+ for (const p of MCP_PRESETS) assert.equal(validateMcpForm(p.form), null, p.id);
+});
+
+test('reads MCP tool names and recorded tool calls', () => {
+ assert.deepEqual(parseMcpToolName('mcp__echo__echo'), { server: 'echo', tool: 'echo' });
+ assert.deepEqual(parseMcpToolName('mcp__my-srv__read__file'), { server: 'my-srv', tool: 'read__file' });
+ assert.equal(parseMcpToolName('Bash'), null);
+
+ const raw = JSON.stringify([
+ { id: 'c1', name: 'mcp__echo__add', arguments: { a: 40, b: 2 }, status: 'ok', result: '42', duration_ms: 3 },
+ { name: 'mcp__echo__echo', server: 'echo', tool: 'echo', status: 'denied' },
+ { nope: true },
+ ]);
+ const calls = parseToolCalls(raw);
+ assert.equal(calls.length, 2);
+ assert.equal(calls[0].server, 'echo');
+ assert.equal(calls[0].tool, 'add');
+ assert.equal(calls[1].status, 'denied');
+ assert.deepEqual(parseToolCalls(null), []);
+ assert.deepEqual(parseToolCalls('not json'), []);
+ assert.equal(parseToolCalls([{ name: 'x' }]).length, 1);
+});
+
+test('formats tool arguments for people', () => {
+ assert.equal(formatArgs({ text: 'hi' }), '{\n "text": "hi"\n}');
+ assert.equal(formatArgs('{"a":1}'), '{\n "a": 1\n}');
+ assert.equal(formatArgs('plain'), 'plain');
+ assert.equal(formatArgs({}), '');
+ assert.equal(formatArgs(undefined), '');
+});
+
+test('says honestly which engines can use MCP tools', () => {
+ const none = { anthropic: false, openai: false, xai: false };
+ assert.equal(mcpSupportFor('claude', none).supported, true);
+ assert.equal(mcpSupportFor('claude', { ...none, anthropic: true }).supported, false);
+ assert.equal(mcpSupportFor('codex', none).supported, false);
+ assert.equal(mcpSupportFor('codex', { ...none, openai: true }).supported, true);
+ assert.equal(mcpSupportFor('grok', none).supported, false);
+ assert.equal(mcpSupportFor('grok', { ...none, xai: true }).supported, true);
+ assert.deepEqual(mcpSupportFor('local_ollama', none), { supported: true, note: null });
+ const auto = mcpSupportFor('auto', none);
+ assert.equal(auto.supported, true);
+ assert.match(auto.note, /Laya/);
+});