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 suggestion card: install, retry, dismiss and sign-in in the chat

Lin (kwant bot)dad7f8848817
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 9daf62eb..d7badd08 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -6,6 +6,8 @@ import { ChatView, ChatMessage, DiscussionState, RoutingState, QueuedState } fro
import { ThreadBar, ThreadHeader } from './components/ThreadBar';
import { DelegationCard } from './components/DelegationCard';
import { QuestionCard } from './components/QuestionCard';
+import { McpSuggestionCard } from './components/McpSuggestionCard';
+import { Suggestion, SuggestionMeta, applySuggestion, suggestionsApi } from './mcpSuggestions';
import { AwayPage } from './components/AwayView';
import { Bot, Check, HelpCircle, Inbox, KeyRound, ListChecks, Loader2, MessageSquare, Settings } from 'lucide-react';
import { PendingApproval } from './components/ModernApprovalCard';
@@ -359,6 +361,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
return next;
});
}, () => undefined);
+ suggestionsApi.list().then((list) => setSuggestions((prev) => list.reduce(applySuggestion, prev)), () => undefined);
try {
const { turns: list } = await threadsApi.turns();
const map = hydrateTurns(list);
@@ -393,6 +396,10 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
const [questions, setQuestions] = useState<Record<string, Question>>({});
const questionsRef = useRef(questions);
questionsRef.current = questions;
+ // Bots' tool suggestions by id (from the list and mcp_suggestion_updated), and installed
+ // servers that still need the person to sign in.
+ const [suggestions, setSuggestions] = useState<Record<string, Suggestion>>({});
+ const [needsSignIn, setNeedsSignIn] = useState<Record<string, boolean>>({});
// Virtual Machine & Live Browser state
const [isVmPaneOpen, setIsVmPaneOpen] = useState(false);
@@ -647,6 +654,12 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
setPendingSkills((prev) => applySkillEvent(prev, sk).filter((x) => x.status === 'pending'));
break;
}
+ case 'mcp_suggestion_updated':
+ case 'McpSuggestionUpdated': {
+ const sg: Suggestion | undefined = event.data?.suggestion;
+ if (sg?.id) setSuggestions((prev) => applySuggestion(prev, sg));
+ break;
+ }
case 'question_updated':
case 'QuestionUpdated': {
const q: Question | undefined = event.data?.question;
@@ -1296,6 +1309,88 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
);
};
+ const handleInstallSuggestion = async (id: string, body: { env?: Record<string, string>; headers?: Record<string, string> }) => {
+ try {
+ const res = await suggestionsApi.install(id, body);
+ setSuggestions((prev) => applySuggestion(prev, res.suggestion));
+ if (res.oauth_required && res.server?.id) setNeedsSignIn((prev) => ({ ...prev, [res.server.id]: true }));
+ return {};
+ } catch (err) {
+ return { error: errText(err) };
+ }
+ };
+ const handleDismissSuggestion = async (id: string): Promise<string | void> => {
+ try {
+ const sg = await suggestionsApi.dismiss(id);
+ setSuggestions((prev) => applySuggestion(prev, sg));
+ } catch (err) {
+ return `Couldn't dismiss it: ${errText(err)}`;
+ }
+ };
+ // Same flow as the servers screen: the window opens inside the click, the address comes after.
+ const handleSuggestionSignIn = async (serverId: string): Promise<string | void> => {
+ const popup = window.open('', 'kwnt-mcp-oauth', 'popup,width=520,height=720');
+ let url: string;
+ try {
+ const res = await fetch(`/api/mcp/servers/${encodeURIComponent(serverId)}/oauth/start`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ origin: window.location.origin }),
+ });
+ const data = await res.json().catch(() => null);
+ if (!res.ok) throw new Error(typeof data?.error === 'string' ? data.error : `Request failed (HTTP ${res.status}).`);
+ if (typeof data?.authorize_url !== 'string' || !/^https?:\/\//.test(data.authorize_url)) throw new Error('The server didn’t return a sign-in page.');
+ url = data.authorize_url;
+ } catch (err) {
+ popup?.close();
+ return `Couldn't start the sign-in: ${errText(err)}`;
+ }
+ if (!popup || popup.closed) {
+ window.location.assign(url);
+ return;
+ }
+ popup.location.href = url;
+ popup.focus();
+ await new Promise<void>((resolve) => {
+ const t = window.setInterval(() => {
+ if (popup.closed) {
+ window.clearInterval(t);
+ resolve();
+ }
+ }, 500);
+ });
+ try {
+ const test = await suggestionsApi.testServer(serverId);
+ if (test.ok) {
+ setNeedsSignIn((prev) => ({ ...prev, [serverId]: false }));
+ return;
+ }
+ return test.auth_required ? 'The sign-in didn’t finish.' : test.error || 'The server still isn’t answering.';
+ } catch (err) {
+ return errText(err);
+ }
+ };
+ const renderMcpSuggestion = (msg: ChatMessage, meta: SuggestionMeta, flash: boolean) => {
+ const live = suggestions[meta.suggestion_id];
+ const owner = live?.kwant_id ?? meta.kwant_id ?? undefined;
+ const name = kwantName(owner);
+ const serverId = live?.server_id ?? meta.server_id;
+ return (
+ <McpSuggestionCard
+ meta={meta}
+ messageId={msg.id}
+ kwantName={name ?? (msg.sender_id && msg.sender_id.length <= 20 ? msg.sender_id : chatTitle)}
+ kwantId={owner}
+ live={live}
+ needsSignIn={!!serverId && !!needsSignIn[serverId]}
+ onInstall={handleInstallSuggestion}
+ onDismiss={handleDismissSuggestion}
+ onSignIn={handleSuggestionSignIn}
+ flash={flash}
+ />
+ );
+ };
+
const renderDelegation = (msg: ChatMessage, meta: DelegationMeta, flash: boolean) => {
const queued = turnsIn(turns, meta.thread_id).find((t) => t.state === 'queued');
return (
@@ -2153,6 +2248,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
queued={queuedHere}
renderDelegation={renderDelegation}
renderQuestion={renderQuestion}
+ renderMcpSuggestion={renderMcpSuggestion}
awaitingAnswer={awaitingHere}
contextKey={openCtx}
/>
diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsx
index 1aebaa50..78a42557 100644
--- a/frontend/src/components/ChatView.tsx
+++ b/frontend/src/components/ChatView.tsx
@@ -11,6 +11,7 @@ import { groupDiscussionThreads, stripDiscussionMarkers } from '../discussionThr
import { PinnedInstructions, PinnedItem } from './Instructions';
import { DelegationMeta, parseDelegationMeta } from '../threads';
import { QuestionMeta, parseQuestionMeta } from '../questions';
+import { SuggestionMeta, parseSuggestionMeta } from '../mcpSuggestions';
import {
AttachmentRef,
MAX_ATTACHMENTS,
@@ -152,6 +153,8 @@ export interface ChatViewProps {
renderDelegation?: (msg: ChatMessage, meta: DelegationMeta, flash: boolean) => React.ReactNode;
/** Draws a bot's question card (messages with `ask_user` meta). */
renderQuestion?: (msg: ChatMessage, meta: QuestionMeta, flash: boolean) => React.ReactNode;
+ /** Draws a bot's tool suggestion card (messages with `mcp_suggestion` meta). */
+ renderMcpSuggestion?: (msg: ChatMessage, meta: SuggestionMeta, flash: boolean) => React.ReactNode;
/** The open chat's turn is paused on a question: it is waiting for the person, not working. */
awaitingAnswer?: boolean;
/** Changes when another chat opens, so the view jumps to its bottom. */
@@ -299,6 +302,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
queued,
renderDelegation,
renderQuestion,
+ renderMcpSuggestion,
awaitingAnswer,
contextKey,
}) => {
@@ -635,6 +639,8 @@ export const ChatView: React.FC<ChatViewProps> = ({
if (meta && renderDelegation) return <React.Fragment key={msg.id}>{renderDelegation(msg, meta, flashId === msg.id)}</React.Fragment>;
const question = msg.meta && renderQuestion ? parseQuestionMeta(msg.meta) : null;
if (question && renderQuestion) return <React.Fragment key={msg.id}>{renderQuestion(msg, question, flashId === msg.id)}</React.Fragment>;
+ const suggestion = msg.meta && renderMcpSuggestion ? parseSuggestionMeta(msg.meta) : null;
+ if (suggestion && renderMcpSuggestion) return <React.Fragment key={msg.id}>{renderMcpSuggestion(msg, suggestion, flashId === msg.id)}</React.Fragment>;
const isUser = msg.sender_role === 'user';
const files = msg.meta ? parseAttachments(msg.meta) : [];
// A bot's share_file note: the file tiles say it all.
diff --git a/frontend/src/components/McpSuggestionCard.tsx b/frontend/src/components/McpSuggestionCard.tsx
new file mode 100644
index 00000000..fb8dab7a
--- /dev/null
+++ b/frontend/src/components/McpSuggestionCard.tsx
@@ -0,0 +1,266 @@
+import React, { useState } from 'react';
+import { AlertTriangle, CheckCircle2, ExternalLink, Globe, KeyRound, Loader2, MinusCircle, Monitor, Plug } from 'lucide-react';
+import { ModernAvatar } from './ModernAvatar';
+import { Suggestion, SuggestionMeta, failureText, inputKey, inputLabel, installPayload, runsLine, suggestionView } from '../mcpSuggestions';
+
+export interface McpSuggestionCardProps {
+ meta: SuggestionMeta;
+ messageId: string;
+ kwantName: string;
+ kwantId?: string;
+ /** Live record from `mcp_suggestion_updated` or the list, when known; wins over `meta`. */
+ live?: Suggestion | null;
+ /** Resolves to an error message on failure; `signIn` true when the server still needs a sign-in. */
+ onInstall: (suggestionId: string, body: { env?: Record<string, string>; headers?: Record<string, string> }) => Promise<{ error?: string; signIn?: boolean }>;
+ onDismiss: (suggestionId: string) => Promise<string | void>;
+ /** Opens the server's sign-in; resolves to an error message, or nothing once signed in. */
+ onSignIn: (serverId: string) => Promise<string | void>;
+ /** The install said this server needs a sign-in that hasn't happened yet. */
+ needsSignIn?: boolean;
+ flash?: boolean;
+}
+
+/**
+ * A bot's suggestion to add a tool server, in the chat. Says what it is, why the bot wants it and
+ * exactly what would run (or which address it connects to); the person types any keys and installs.
+ * A failed install keeps the form and its values so they can fix a key and try again.
+ */
+export const McpSuggestionCard: React.FC<McpSuggestionCardProps> = ({
+ meta,
+ messageId,
+ kwantName,
+ kwantId,
+ live,
+ onInstall,
+ onDismiss,
+ onSignIn,
+ needsSignIn,
+ flash,
+}) => {
+ const view = suggestionView(meta, live);
+ const [values, setValues] = useState<Record<string, string>>({});
+ const [busy, setBusy] = useState<'install' | 'dismiss' | 'signin' | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [dismissError, setDismissError] = useState<string | null>(null);
+ const [signInError, setSignInError] = useState<string | null>(null);
+
+ const headingId = `mcp-s-${messageId}`;
+ const pending = view.status === 'pending' && busy !== 'install';
+ const installing = view.status === 'installing' || busy === 'install';
+ const failure = error ?? (view.status === 'pending' ? view.last_error : null);
+ const runs = runsLine(view);
+ const local = view.runs_on_your_computer || view.transport === 'stdio';
+
+ const install = async () => {
+ if (!pending || busy) return;
+ const { body, missing } = installPayload(view.inputs, values);
+ if (missing.length) {
+ setError(`Fill in ${missing.join(', ')} first.`);
+ return;
+ }
+ setBusy('install');
+ setError(null);
+ const res = await onInstall(view.suggestion_id, body);
+ setBusy(null);
+ if (res.error) setError(res.error);
+ else setValues({});
+ };
+
+ const dismiss = async () => {
+ if (!pending || busy) return;
+ setBusy('dismiss');
+ setDismissError(null);
+ const err = await onDismiss(view.suggestion_id);
+ setBusy(null);
+ if (err) setDismissError(err);
+ };
+
+ const signIn = async () => {
+ if (!view.server_id || busy) return;
+ setBusy('signin');
+ setSignInError(null);
+ const err = await onSignIn(view.server_id);
+ setBusy(null);
+ if (err) setSignInError(err);
+ };
+
+ const border =
+ view.status === 'installed' ? 'border-emerald-500/30' : view.status === 'dismissed' ? 'border-zinc-800' : failure ? 'border-rose-500/40' : 'border-sky-500/35';
+
+ return (
+ <section data-message-id={messageId} aria-labelledby={headingId} className={`flex items-start gap-3.5 w-full max-w-5xl rounded-xl ${flash ? 'kw-flash' : ''}`}>
+ <ModernAvatar role={kwantName} name={kwantName} size={34} kwantId={kwantId} />
+ <div className={`flex-1 min-w-0 max-w-2xl rounded-2xl rounded-tl-sm border bg-zinc-900/60 shadow-sm ${border}`}>
+ <div className="px-4 pt-3 pb-2 space-y-1.5">
+ <span className="flex items-center gap-1.5 text-[11px] font-medium text-zinc-400">
+ <Plug size={12} className="text-sky-300" aria-hidden="true" />
+ <span className="text-zinc-200">{kwantName}</span> suggests a tool
+ </span>
+ <div className="flex flex-wrap items-baseline gap-x-2 gap-y-1">
+ <h3 id={headingId} className="text-sm font-semibold text-zinc-100 break-words leading-snug">
+ {view.title}
+ </h3>
+ {view.version && <span className="text-[11px] text-zinc-500">v{view.version}</span>}
+ </div>
+ {view.description && <p className="text-sm text-zinc-300 break-words leading-relaxed">{view.description}</p>}
+ {view.reason && (
+ <p className="text-sm text-zinc-300 break-words leading-relaxed">
+ <span className="text-zinc-500">Why: </span>
+ {view.reason}
+ </p>
+ )}
+ </div>
+
+ <div className="mx-4 mb-2 rounded-xl border border-zinc-800 bg-zinc-950/70 px-3 py-2 space-y-1.5">
+ <div className="flex flex-wrap items-center gap-2 text-[11px]">
+ {local ? (
+ <span className="inline-flex items-center gap-1 rounded-full border border-amber-500/40 bg-amber-500/10 px-2 py-0.5 font-medium text-amber-200">
+ <Monitor size={11} aria-hidden="true" /> Runs on your computer
+ </span>
+ ) : (
+ <span className="inline-flex items-center gap-1 rounded-full border border-sky-500/30 bg-sky-500/10 px-2 py-0.5 font-medium text-sky-200">
+ <Globe size={11} aria-hidden="true" /> Online service
+ </span>
+ )}
+ {view.repository_url && (
+ <a
+ href={view.repository_url}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="inline-flex items-center gap-1 text-zinc-400 hover:text-zinc-200 underline-offset-2 hover:underline rounded focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400"
+ >
+ Source code <ExternalLink size={11} aria-hidden="true" />
+ <span className="sr-only">(opens in a new tab)</span>
+ </a>
+ )}
+ </div>
+ <p className="text-[11px] text-zinc-500">{local ? 'Installing runs this command:' : 'Installing connects to:'}</p>
+ <code className="block text-xs text-zinc-200 font-mono break-all whitespace-pre-wrap">{runs || 'Unknown'}</code>
+ {(view.fixed_env.length > 0 || view.fixed_headers.length > 0) && (
+ <p className="text-[11px] text-zinc-500 break-words">
+ Also sets: {[...view.fixed_env, ...view.fixed_headers].join(', ')}
+ </p>
+ )}
+ </div>
+
+ {view.status === 'pending' || installing ? (
+ <form
+ className="px-4 pb-2 space-y-2.5"
+ autoComplete="off"
+ onSubmit={(e) => {
+ e.preventDefault();
+ install();
+ }}
+ >
+ {view.inputs.map((i) => {
+ const key = inputKey(i);
+ const id = `${headingId}-${key}`;
+ const { label, code, note } = inputLabel(i);
+ return (
+ <div key={key} className="space-y-1">
+ <label htmlFor={id} className="flex flex-wrap items-center gap-1.5 text-xs text-zinc-300">
+ {i.secret && <KeyRound size={11} className="text-zinc-500" aria-hidden="true" />}
+ <span className={code ? 'font-mono' : 'font-medium'}>{label}</span>
+ {!i.required && <span className="text-zinc-500">(optional)</span>}
+ </label>
+ {(i.description || note) && (
+ <p id={`${id}-hint`} className="text-[11px] text-zinc-500 break-words">
+ {[i.description, note].filter(Boolean).join(' · ')}
+ </p>
+ )}
+ <input
+ id={id}
+ type={i.secret ? 'password' : 'text'}
+ autoComplete={i.secret ? 'new-password' : 'off'}
+ spellCheck={false}
+ data-1p-ignore
+ data-lpignore="true"
+ required={i.required}
+ aria-describedby={i.description || note ? `${id}-hint` : undefined}
+ aria-invalid={!!failure || undefined}
+ disabled={installing || busy !== null}
+ value={values[key] ?? ''}
+ placeholder={i.placeholder && !i.secret ? i.placeholder : i.secret ? 'Paste it here' : ''}
+ onChange={(e) => setValues((v) => ({ ...v, [key]: e.target.value }))}
+ className="w-full min-h-[40px] sm:min-h-[34px] rounded-lg bg-zinc-950 border border-zinc-800 px-2.5 py-1.5 text-sm text-zinc-100 placeholder-zinc-600 focus:outline-none focus:border-sky-500/60 disabled:opacity-60"
+ />
+ </div>
+ );
+ })}
+ {failure && (
+ <p role="alert" className="flex items-start gap-1.5 rounded-lg border border-rose-500/30 bg-rose-500/10 px-2.5 py-1.5 text-xs text-rose-200 break-words">
+ <AlertTriangle size={13} className="mt-px shrink-0" aria-hidden="true" />
+ <span>It didn’t install. {failureText(failure, view.inputs.length > 0)}</span>
+ </p>
+ )}
+ <div className="flex flex-wrap items-center gap-2 pt-0.5">
+ <button
+ type="submit"
+ disabled={busy !== null || installing}
+ className="inline-flex items-center justify-center gap-1.5 min-h-[40px] sm:min-h-[34px] px-3.5 rounded-xl text-sm font-medium bg-sky-500 text-zinc-950 hover:bg-sky-400 disabled:bg-zinc-800 disabled:text-zinc-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-400"
+ >
+ {installing && <Loader2 size={13} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />}
+ {installing ? 'Installing and testing…' : failure ? 'Try again' : 'Install'}
+ </button>
+ <button
+ type="button"
+ onClick={dismiss}
+ disabled={busy !== null || installing}
+ className="min-h-[40px] sm:min-h-[34px] px-3 rounded-xl text-sm text-zinc-300 border border-zinc-700 hover:bg-zinc-800 disabled:opacity-50 focus-visible:outline focus-visible:outline-2 focus-visible:outline-zinc-500"
+ >
+ {busy === 'dismiss' ? 'Saying no…' : 'Not now'}
+ </button>
+ </div>
+ </form>
+ ) : null}
+
+ <div className="px-4 pb-3 pt-0.5 text-[11px] space-y-1.5">
+ <p role="status" aria-live="polite" className="min-w-0">
+ {view.status === 'installed' ? (
+ needsSignIn ? (
+ <span className="inline-flex items-center gap-1.5 text-amber-200">
+ <KeyRound size={13} aria-hidden="true" /> Installed. Sign in to {view.title} so {kwantName} can use it.
+ </span>
+ ) : (
+ <span className="inline-flex items-center gap-1.5 text-emerald-300">
+ <CheckCircle2 size={13} aria-hidden="true" /> Ready. {kwantName} can use it from its next reply.
+ </span>
+ )
+ ) : view.status === 'dismissed' ? (
+ <span className="inline-flex items-center gap-1.5 text-zinc-400">
+ <MinusCircle size={13} aria-hidden="true" /> Not installed. {kwantName} carries on without it.
+ </span>
+ ) : installing ? (
+ <span className="sr-only">Installing and testing…</span>
+ ) : (
+ <span className="text-zinc-500">Only you can install it. Keys you type are saved hidden and never appear in the chat.</span>
+ )}
+ </p>
+ {view.status === 'installed' && needsSignIn && view.server_id && (
+ <div className="flex flex-wrap items-center gap-2">
+ <button
+ type="button"
+ onClick={signIn}
+ disabled={busy !== null}
+ className="inline-flex items-center gap-1.5 min-h-[40px] sm:min-h-[34px] px-3.5 rounded-xl text-sm font-medium bg-amber-500 text-zinc-950 hover:bg-amber-400 disabled:opacity-60 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-amber-400"
+ >
+ {busy === 'signin' && <Loader2 size={13} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />}
+ {busy === 'signin' ? 'Waiting for sign-in…' : signInError ? 'Try signing in again' : 'Sign in'}
+ </button>
+ {signInError && (
+ <span role="alert" className="text-rose-300 break-words">
+ {signInError}
+ </span>
+ )}
+ </div>
+ )}
+ {dismissError && (
+ <p role="alert" className="text-rose-300 break-words">
+ {dismissError}
+ </p>
+ )}
+ </div>
+ </div>
+ </section>
+ );
+};
diff --git a/frontend/src/mcpSuggestions.ts b/frontend/src/mcpSuggestions.ts
new file mode 100644
index 00000000..7498b793
--- /dev/null
+++ b/frontend/src/mcpSuggestions.ts
@@ -0,0 +1,218 @@
+// MCP suggestions: a bot found a tool server it needs and suggests it; only the person installs it.
+// Contract: docs/mcp-api.md → "Suggestions".
+import { parseMetaObject } from './questions';
+import { McpServer, McpTestResult, joinCommandLine } from './mcp';
+import { request } from './threads';
+
+export type SuggestionStatus = 'pending' | 'installing' | 'installed' | 'dismissed';
+
+export interface SuggestionInput {
+ name: string;
+ kind: 'env' | 'header';
+ description: string;
+ required: boolean;
+ secret: boolean;
+ /** e.g. `Bearer {api_key}`: the person types only the part in braces. */
+ template: string | null;
+ placeholder: string | null;
+}
+
+/** `meta` of the card message (`kind: "mcp_suggestion"`); never holds secret values. */
+export interface SuggestionMeta {
+ kind: 'mcp_suggestion';
+ suggestion_id: string;
+ kwant_id: string | null;
+ registry_name: string;
+ version: string;
+ title: string;
+ description: string;
+ reason: string;
+ repository_url: string | null;
+ transport: 'http' | 'stdio' | null;
+ url: string | null;
+ command: string | null;
+ args: string[];
+ package: string | null;
+ runs_on_your_computer: boolean;
+ fixed_env: string[];
+ fixed_headers: string[];
+ inputs: SuggestionInput[];
+ status: SuggestionStatus;
+ server_id: string | null;
+ last_error: string | null;
+}
+
+/** A suggestion record from the API or `mcp_suggestion_updated`; `card` is its meta. */
+export interface Suggestion {
+ id: string;
+ kwant_id: string;
+ status: SuggestionStatus;
+ server_id: string | null;
+ last_error: string | null;
+ message_id: string | null;
+ created_at: string;
+ card?: unknown;
+}
+
+export interface InstallResult {
+ suggestion: Suggestion;
+ server: McpServer;
+ test: McpTestResult;
+ oauth_required: boolean;
+}
+
+const str = (v: unknown): string | null => (typeof v === 'string' && v ? v : null);
+const strs = (v: unknown): string[] => (Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : []);
+const STATUSES: SuggestionStatus[] = ['pending', 'installing', 'installed', 'dismissed'];
+
+function parseInput(raw: unknown): SuggestionInput | null {
+ if (!raw || typeof raw !== 'object') return null;
+ const i = raw as Record<string, unknown>;
+ const name = str(i.name);
+ if (!name || (i.kind !== 'env' && i.kind !== 'header')) return null;
+ return {
+ name,
+ kind: i.kind,
+ description: str(i.description) ?? '',
+ required: i.required === true,
+ secret: i.secret !== false,
+ template: str(i.template),
+ placeholder: str(i.placeholder),
+ };
+}
+
+export function parseSuggestionMeta(raw: unknown): SuggestionMeta | null {
+ const m = parseMetaObject(raw);
+ if (!m || m.kind !== 'mcp_suggestion') return null;
+ const id = str(m.suggestion_id);
+ const name = str(m.registry_name);
+ if (!id || !name) return null;
+ return {
+ kind: 'mcp_suggestion',
+ suggestion_id: id,
+ kwant_id: str(m.kwant_id),
+ registry_name: name,
+ version: str(m.version) ?? '',
+ title: str(m.title) ?? name,
+ description: str(m.description) ?? '',
+ reason: str(m.reason) ?? '',
+ repository_url: safeLink(str(m.repository_url)),
+ transport: m.transport === 'http' || m.transport === 'stdio' ? m.transport : null,
+ url: str(m.url),
+ command: str(m.command),
+ args: strs(m.args),
+ package: str(m.package),
+ runs_on_your_computer: m.runs_on_your_computer === true,
+ fixed_env: strs(m.fixed_env),
+ fixed_headers: strs(m.fixed_headers),
+ inputs: Array.isArray(m.inputs) ? m.inputs.map(parseInput).filter((x): x is SuggestionInput => !!x) : [],
+ status: STATUSES.includes(m.status as SuggestionStatus) ? (m.status as SuggestionStatus) : 'pending',
+ server_id: str(m.server_id),
+ last_error: str(m.last_error),
+ };
+}
+
+/** Registry text is untrusted: only http(s) links become clickable. */
+export function safeLink(url: string | null): string | null {
+ if (!url) return null;
+ try {
+ const u = new URL(url);
+ return u.protocol === 'https:' || u.protocol === 'http:' ? u.href : null;
+ } catch {
+ return null;
+ }
+}
+
+/** Card state: the live record (newer card meta) wins over the message's meta. */
+export function suggestionView(meta: SuggestionMeta, live?: Suggestion | null): SuggestionMeta {
+ if (!live || live.id !== meta.suggestion_id) return meta;
+ const card = parseSuggestionMeta(live.card);
+ const base = card ?? meta;
+ return { ...base, status: live.status, server_id: live.server_id, last_error: live.last_error };
+}
+
+const RANK: Record<SuggestionStatus, number> = { pending: 0, installing: 1, installed: 2, dismissed: 2 };
+
+/** Keeps the latest record per suggestion; a finished one never goes back to pending. */
+export function applySuggestion(map: Record<string, Suggestion>, s: Suggestion): Record<string, Suggestion> {
+ const prev = map[s.id];
+ if (prev && RANK[prev.status] === 2 && RANK[s.status] < 2) return map;
+ return { ...map, [s.id]: s };
+}
+
+/** What installing runs, in one line: the address, or the exact command. */
+export function runsLine(m: Pick<SuggestionMeta, 'url' | 'command' | 'args'>): string {
+ if (m.url) return m.url;
+ return m.command ? joinCommandLine([m.command, ...m.args]) : '';
+}
+
+/** The single `{name}` in a template like `Bearer {api_key}`, else null. */
+export function templateSlot(template: string | null): string | null {
+ if (!template) return null;
+ const all = template.match(/\{[^{}]+\}/g);
+ return all && all.length === 1 ? all[0].slice(1, -1) : null;
+}
+
+const WORDS: Record<string, string> = { api: 'API', id: 'ID', url: 'URL', pat: 'PAT', oauth: 'OAuth' };
+
+/** `api_key` → `API key`, `accessToken` → `Access token`. */
+export function humanizeSlot(slot: string): string {
+ const words = slot
+ .replace(/([a-z])([A-Z])/g, '$1 $2')
+ .split(/[\s_-]+/)
+ .filter(Boolean)
+ .map((w) => WORDS[w.toLowerCase()] ?? w.toLowerCase());
+ const s = words.join(' ');
+ return s ? s.charAt(0).toUpperCase() + s.slice(1) : slot;
+}
+
+/** How a field is labelled: a template asks for its one slot (the key), else the variable's name. */
+export function inputLabel(i: SuggestionInput): { label: string; code: boolean; note: string | null } {
+ const slot = templateSlot(i.template);
+ if (slot) {
+ const label = humanizeSlot(slot);
+ return { label, code: false, note: `Sent as the ${i.name} ${i.kind === 'header' ? 'header' : 'setting'}: ${i.template!.replace(`{${slot}}`, `<${label.toLowerCase()}>`)}` };
+ }
+ return { label: i.name, code: true, note: null };
+}
+
+export const inputKey = (i: Pick<SuggestionInput, 'kind' | 'name'>) => `${i.kind}:${i.name}`;
+
+/** The install body: trimmed, blank optional fields left out. Missing required names → `missing`. */
+export function installPayload(
+ inputs: SuggestionInput[],
+ values: Record<string, string>,
+): { body: { env?: Record<string, string>; headers?: Record<string, string> }; missing: string[] } {
+ const env: Record<string, string> = {};
+ const headers: Record<string, string> = {};
+ const missing: string[] = [];
+ for (const i of inputs) {
+ const v = (values[inputKey(i)] ?? '').trim();
+ if (!v) {
+ if (i.required) missing.push(inputLabel(i).label);
+ continue;
+ }
+ (i.kind === 'env' ? env : headers)[i.name] = v;
+ }
+ const body: { env?: Record<string, string>; headers?: Record<string, string> } = {};
+ if (Object.keys(env).length) body.env = env;
+ if (Object.keys(headers).length) body.headers = headers;
+ return { body, missing };
+}
+
+/** A failed install in plain words: a refused key says so instead of the server's transport error. */
+export function failureText(raw: string, asksForKeys: boolean): string {
+ if (asksForKeys && /\b(401|403)\b|unauthori[sz]ed|forbidden/i.test(raw)) return 'The server turned down the key. Check it and try again.';
+ return `${raw.trim().replace(/\.?$/, '.')}${asksForKeys ? ' Check what you typed and try again.' : ' You can try again.'}`;
+}
+
+const enc = encodeURIComponent;
+
+export const suggestionsApi = {
+ list: (status?: SuggestionStatus) => request<Suggestion[]>('GET', `/api/mcp/suggestions${status ? `?status=${status}` : ''}`),
+ install: (id: string, body: { env?: Record<string, string>; headers?: Record<string, string> }) =>
+ request<InstallResult>('POST', `/api/mcp/suggestions/${enc(id)}/install`, body),
+ dismiss: (id: string) => request<Suggestion>('POST', `/api/mcp/suggestions/${enc(id)}/dismiss`),
+ /** Re-checks an installed server, e.g. after its sign-in window closes. */
+ testServer: (serverId: string) => request<McpTestResult>('POST', `/api/mcp/servers/${enc(serverId)}/test`),
+};
diff --git a/frontend/tests/mcpSuggestions.test.mjs b/frontend/tests/mcpSuggestions.test.mjs
new file mode 100644
index 00000000..2abad68e
--- /dev/null
+++ b/frontend/tests/mcpSuggestions.test.mjs
@@ -0,0 +1,135 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { loadBundled } from './bundle.mjs';
+
+const s = await loadBundled(`export * from './src/mcpSuggestions';`);
+const ui = await loadBundled(`
+ import React from 'react';
+ import { renderToStaticMarkup } from 'react-dom/server.browser';
+ import { McpSuggestionCard } from './src/components/McpSuggestionCard';
+ export const render = (props) => renderToStaticMarkup(React.createElement(McpSuggestionCard, props));
+`);
+
+const httpMeta = (over = {}) => ({
+ kind: 'mcp_suggestion', suggestion_id: 's1', kwant_id: 'k1', registry_name: 'io.example/echo', version: '1.2.0',
+ title: 'Echo', description: 'Repeats what you send.', reason: 'You asked me to echo things.',
+ repository_url: 'https://github.com/example/echo', transport: 'http', url: 'https://echo.example/mcp',
+ command: null, args: [], package: null, runs_on_your_computer: false, fixed_env: [], fixed_headers: [],
+ inputs: [{ name: 'Authorization', kind: 'header', description: 'Your Echo key', required: true, secret: true, template: 'Bearer {api_key}', placeholder: null }],
+ status: 'pending', server_id: null, last_error: null, ...over,
+});
+const stdioMeta = (over = {}) =>
+ httpMeta({
+ transport: 'stdio', url: null, command: 'npx', args: ['-y', '@example/[email protected]'], package: 'npm @example/[email protected]',
+ runs_on_your_computer: true, fixed_env: ['LOG_LEVEL'],
+ inputs: [{ name: 'ECHO_KEY', kind: 'env', description: 'Key', required: true, secret: true, template: null, placeholder: null },
+ { name: 'ECHO_REGION', kind: 'env', description: '', required: false, secret: false, template: null, placeholder: 'eu' }],
+ ...over,
+ });
+const noop = async () => ({});
+const props = (meta, over = {}) => ({
+ meta: s.parseSuggestionMeta(meta), messageId: 'm1', kwantName: 'Scout', kwantId: 'k1',
+ onInstall: noop, onDismiss: async () => {}, onSignIn: async () => {}, ...over,
+});
+
+test('card meta parses from a string or object and ignores other kinds', () => {
+ const m = s.parseSuggestionMeta(JSON.stringify(httpMeta()));
+ assert.equal(m.title, 'Echo');
+ assert.equal(m.inputs[0].template, 'Bearer {api_key}');
+ assert.equal(s.parseSuggestionMeta({ kind: 'ask_user', question_id: 'q' }), null);
+ assert.equal(s.parseSuggestionMeta('nope'), null);
+ assert.equal(s.parseSuggestionMeta({ kind: 'mcp_suggestion' }), null, 'needs an id and a name');
+ assert.equal(s.parseSuggestionMeta(httpMeta({ status: 'weird' })).status, 'pending');
+ assert.equal(s.parseSuggestionMeta(httpMeta({ inputs: [{ name: 'X', kind: 'cookie' }, 3] })).inputs.length, 0);
+});
+
+test('registry links are only clickable when they are http(s)', () => {
+ assert.equal(s.parseSuggestionMeta(httpMeta({ repository_url: 'javascript:alert(1)' })).repository_url, null);
+ assert.equal(s.parseSuggestionMeta(httpMeta({ repository_url: 'not a url' })).repository_url, null);
+ assert.equal(s.safeLink('https://github.com/x'), 'https://github.com/x');
+});
+
+test('the live record wins; a finished suggestion never goes back to pending', () => {
+ const m = s.parseSuggestionMeta(httpMeta());
+ const live = { id: 's1', kwant_id: 'k1', status: 'installed', server_id: 'srv', last_error: null, message_id: 'm1', created_at: 'x' };
+ assert.equal(s.suggestionView(m, live).status, 'installed');
+ assert.equal(s.suggestionView(m, { ...live, id: 'other' }).status, 'pending');
+ let map = s.applySuggestion({}, live);
+ map = s.applySuggestion(map, { ...live, status: 'pending' });
+ assert.equal(map.s1.status, 'installed');
+ map = s.applySuggestion({}, { ...live, status: 'installing' });
+ map = s.applySuggestion(map, { ...live, status: 'pending', last_error: 'bad key' });
+ assert.equal(map.s1.last_error, 'bad key', 'a failed install returns to pending with its error');
+});
+
+test('a template asks only for the key; the body carries what was typed, trimmed', () => {
+ const [auth] = s.parseSuggestionMeta(httpMeta()).inputs;
+ const l = s.inputLabel(auth);
+ assert.equal(l.label, 'API key');
+ assert.match(l.note, /Bearer <api key>/);
+ assert.deepEqual(s.installPayload([auth], { 'header:Authorization': ' abc ' }), { body: { headers: { Authorization: 'abc' } }, missing: [] });
+ assert.deepEqual(s.installPayload([auth], {}).missing, ['API key']);
+ const env = s.parseSuggestionMeta(stdioMeta()).inputs;
+ assert.deepEqual(s.installPayload(env, { 'env:ECHO_KEY': 'k', 'env:ECHO_REGION': ' ' }).body, { env: { ECHO_KEY: 'k' } }, 'blank optional fields are left out');
+ assert.equal(s.inputLabel(env[0]).label, 'ECHO_KEY');
+ assert.equal(s.humanizeSlot('accessToken'), 'Access token');
+ assert.equal(s.templateSlot('{a} {b}'), null, 'several slots: typed as is');
+});
+
+test('http card: online service, the address, a password field for the key, Install and Not now', () => {
+ const html = ui.render(props(httpMeta()));
+ assert.match(html, /Scout<\/span> suggests a tool/);
+ assert.match(html, /Online service/);
+ assert.doesNotMatch(html, /Runs on your computer/);
+ assert.match(html, /Installing connects to:/);
+ assert.match(html, /https:\/\/echo\.example\/mcp/);
+ assert.match(html, /You asked me to echo things\./);
+ assert.match(html, /type="password"[^>]*autoComplete="new-password"|autoComplete="new-password"[^>]*type="password"/);
+ assert.match(html, />API key</);
+ assert.match(html, />Install</);
+ assert.match(html, />Not now</);
+ assert.match(html, /href="https:\/\/github\.com\/example\/echo"[^>]*rel="noopener noreferrer"/);
+});
+
+test('stdio card: "Runs on your computer" with the exact command; optional fields say so', () => {
+ const html = ui.render(props(stdioMeta()));
+ assert.match(html, /Runs on your computer/);
+ assert.match(html, /Installing runs this command:/);
+ assert.match(html, /npx -y @example\/echo-mcp@1\.2\.0/);
+ assert.match(html, /Also sets: LOG_LEVEL/);
+ assert.match(html, /\(optional\)/);
+ assert.match(html, /type="text"[^>]*placeholder="eu"/);
+});
+
+test('a failed install keeps the form and offers to try again', () => {
+ const html = ui.render(props(httpMeta({ last_error: "The server didn't start: transport error: HTTP 401 Unauthorized (sign in to this server from the Tools screen)" })));
+ assert.match(html, /role="alert"[^>]*>.*It didn’t install\. The server turned down the key\. Check it and try again\./s);
+ assert.doesNotMatch(html, /Tools screen|transport error/);
+ assert.match(html, />Try again</);
+ assert.match(html, /type="password"/, 'the field is still there');
+});
+
+test('failure wording: a refused key is named; other errors keep their detail', () => {
+ const raw = "The server didn't start: transport error: HTTP 401 Unauthorized (sign in to this server from the Tools screen)";
+ assert.equal(s.failureText(raw, true), 'The server turned down the key. Check it and try again.');
+ assert.equal(s.failureText("The server didn't start: connection refused", true), "The server didn't start: connection refused. Check what you typed and try again.");
+ assert.equal(s.failureText("The server didn't start: timed out.", false), "The server didn't start: timed out. You can try again.");
+});
+
+test('installing, installed, needs sign-in and dismissed states', () => {
+ const installing = ui.render(props(httpMeta({ status: 'installing' })));
+ assert.match(installing, /Installing and testing…/);
+ assert.match(installing, /disabled=""/);
+
+ const ready = ui.render(props(httpMeta({ status: 'installed', server_id: 'srv' })));
+ assert.match(ready, /Ready\. Scout can use it from its next reply\./);
+ assert.doesNotMatch(ready, /type="password"|>Install</);
+
+ const signIn = ui.render(props(httpMeta({ status: 'installed', server_id: 'srv' }), { needsSignIn: true }));
+ assert.match(signIn, /Sign in to Echo so Scout can use it/);
+ assert.match(signIn, />Sign in</);
+
+ const no = ui.render(props(httpMeta({ status: 'dismissed' })));
+ assert.match(no, /Not installed\. Scout carries on without it\./);
+ assert.doesNotMatch(no, /<form/);
+});