Files
Agent-Workbench/src/client/McpPanel.tsx
T

148 lines
16 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useEffect, useRef, useState } from 'react';
import type { FormEvent } from 'react';
import { AlertTriangle, Check, CircleAlert, Fingerprint, LoaderCircle, PlugZap, Plus, Power, RefreshCw, ShieldCheck, Terminal } from 'lucide-react';
import type { McpJob, McpRegistration, Session } from './types';
import { api } from './api';
import { Modal } from './components';
import { McpJobHistory } from './McpJobHistory';
import { useRecordPages } from './useRecordPages';
import { approvalLabels, mcpPermissionContext } from '../shared/contracts/execution-policy.mjs';
import './McpPanel.css';
const active = ['queued', 'connecting', 'discovering', 'calling', 'closing', 'stopping'];
const stateName: Record<string, string> = { verified: '握手已核验', unverified: '尚未探测', changed: '来源或契约异常' };
type View = { projectId: string; revision: number; protocolVersion: string; boundary: string; executionMode: string; limits: Record<string, number | null>; registrations: McpRegistration[] };
type Draft = { name: string; executable: string; entry: string; timeoutMs: number };
export function McpPanel({ projectId, session, busy, approvalMode = 'ask', onSession, onError }: {
projectId: string; session: Session | null; busy: boolean; approvalMode?: 'ask' | 'auto' | 'full'; onSession: (value: Session) => void; onError: (error: unknown) => void;
}) {
const [view, setView] = useState<View | null>(null);
const history = useRecordPages<McpJob>(session ? '/sessions/' + session.id + '/mcp/jobs' : null, onError), jobs = history.items;
const [working, setWorking] = useState(false), [error, setError] = useState(''), [notice, setNotice] = useState('');
const [selectedTools, setSelectedTools] = useState<Record<string, string[]>>({});
const [draft, setDraft] = useState<Draft>({ name: '', executable: '', entry: '', timeoutMs: 15000 });
const [probeTarget, setProbeTarget] = useState<McpRegistration | null>(null);
const [requestError, setRequestError] = useState('');
const generation = useRef(0), revisions = useRef(new Map<string, number>()), mounted = useRef(true);
const url = '/projects/' + projectId + '/mcp';
const busyJobs = jobs.some(job => active.includes(job.status));
const locked = busy || busyJobs || working;
const permission = mcpPermissionContext({ approvalMode }).action === 'execute' ? '任务中的已启用调用直接执行。' : '外部工具调用由工作台请求批准。';
useEffect(() => { mounted.current = true; return () => { mounted.current = false; generation.current++; }; }, []);
async function load(current = generation.current) {
const [nextView] = await Promise.all([api<View>(url), history.refresh()]);
if (!mounted.current || current !== generation.current) return;
setView(nextView);
setSelectedTools(previous => {
const next = { ...previous };
for (const registration of nextView.registrations) if (revisions.current.get(registration.id) !== registration.configurationRevision) {
next[registration.id] = [...registration.allowedTools]; revisions.current.set(registration.id, registration.configurationRevision);
}
return next;
});
}
useEffect(() => {
const current = ++generation.current; setView(null); setError(''); setNotice(''); setProbeTarget(null);
void load(current).catch(cause => { if (mounted.current && generation.current === current) setError(cause instanceof Error ? cause.message : String(cause)); });
return () => { if (generation.current === current) generation.current++; };
}, [projectId, session?.id]);
useEffect(() => {
if (!session || !jobs.some(job => active.includes(job.status))) return;
const current = generation.current;
const timer = window.setInterval(() => { void Promise.all([history.refresh(), api<View>(url)]).then(([, nextView]) => {
if (mounted.current && generation.current === current) setView(nextView);
}).catch(cause => { if (generation.current === current) setError(cause instanceof Error ? cause.message : String(cause)); }); }, 900);
return () => window.clearInterval(timer);
}, [jobs, projectId, session?.id]);
async function perform(action: () => Promise<unknown>, message: string) {
const current = generation.current; setWorking(true); setError(''); setNotice('');
try { await action(); if (current === generation.current) { setNotice(message); await load(current); } }
catch (cause) { if (current === generation.current) setError(cause instanceof Error ? cause.message : String(cause)); }
finally { if (current === generation.current) setWorking(false); }
}
function register(event: FormEvent) {
event.preventDefault();
void perform(async () => {
await api(url, { name: draft.name.trim(), executable: draft.executable.trim(), ...(draft.entry.trim() ? { entry: draft.entry.trim() } : {}), timeoutMs: draft.timeoutMs });
setDraft({ name: '', executable: '', entry: '', timeoutMs: 15000 });
}, '程序已登记并保持停用。请先实际探测,再选择允许的工具。');
}
async function probe() {
if (!probeTarget || !session) return;
const target = probeTarget; setWorking(true); setError(''); setNotice(''); setRequestError('');
try {
const result = await api<{ job: McpJob; session: Session }>('/sessions/' + session.id + '/mcp/probe', { id: target.id, configurationRevision: target.configurationRevision, confirm: true });
onSession(result.session); setProbeTarget(null); setNotice('探测已启动;完成后根据实际握手和参数契约选择工具。');
const current = generation.current; await load(current);
} catch (cause) { setRequestError(cause instanceof Error ? cause.message : String(cause)); }
finally { setWorking(false); }
}
async function stop() {
if (!session) return;
await perform(async () => { const updated = await api<Session>('/sessions/' + session.id + '/mcp/stop', {}); onSession(updated); }, 'MCP 操作已停止,已发出的调用若没有结果会保留为待核对。');
}
const saveTools = (registration: McpRegistration) => perform(async () => {
const value = await api<McpRegistration>(url + '/configure', { id: registration.id, configurationRevision: registration.configurationRevision,
enabled: !!selectedTools[registration.id]?.length, allowedTools: selectedTools[registration.id] ?? [] });
revisions.current.set(value.id, -1);
}, selectedTools[registration.id]?.length ? '已保存所选工具并启用。' + permission : '已停用该 MCP。');
const disable = (registration: McpRegistration) => perform(async () => {
await api(url + '/configure', { id: registration.id, configurationRevision: registration.configurationRevision, enabled: false, allowedTools: [] });
revisions.current.set(registration.id, -1);
}, '该 MCP 已停用,后续请求不会再发送它的工具目录。');
return <section className="mcp-panel" aria-label="项目MCP工具管理" aria-busy={working}>
<header className="mcp-heading"><div><span className="mcp-kicker"><PlugZap size={15} />项目能力 / MCP</span><h3>连接外部工具</h3><p>登记本地 stdio 程序,探测实际握手后选择工具。{approvalMode === 'full' ? '完全访问权限下,任务中的已启用调用直接执行。' : '外部工具调用由工作台请求批准,提交调用后即可处理。'}</p></div>
<button type="button" className="button secondary" disabled={working} onClick={() => void perform(() => load(), '项目 MCP 状态已重新核对。')}><RefreshCw size={14} className={working ? 'spin' : ''} />刷新</button></header>
<div className="mcp-status-bar"><span><i className="mcp-light" />{view?.registrations.filter(item => item.enabled && item.status === 'verified').length ?? 0} 项已启用</span><span>{view?.registrations.length ?? 0} 项已登记</span><span>协议 {view?.protocolVersion ?? '2025-03-26'}</span><span><ShieldCheck size={14} />{approvalLabels[approvalMode]} · {approvalMode === 'full' ? '直接执行' : '请求批准'}</span></div>
{error && <p className="mcp-alert" role="alert"><CircleAlert size={16} />{error}</p>}
{notice && <p className="mcp-notice" role="status"><Check size={16} />{notice}</p>}
{busy && <p className="mcp-warning">当前项目正在执行;完成或停止后才能修改 MCP 配置。</p>}
<div className="mcp-boundary"><ShieldCheck size={16} /><span>{view?.boundary ?? '每次操作使用独立所属进程。进程隔离不等于 OS 沙箱,外部服务和程序可能拥有自己的网络或副作用。'}</span></div>
{view?.registrations.length ? <div className="mcp-registration-list">{view.registrations.map(registration => {
const chosen = selectedTools[registration.id] ?? registration.allowedTools;
return <article className={'mcp-registration status-' + registration.status} key={registration.id}>
<div className="mcp-registration-heading"><Terminal size={18} /><div><h4>{registration.name}</h4><p>{stateName[registration.status] ?? registration.status} · 配置修订 {registration.configurationRevision}</p></div><span className={'mcp-enabled ' + (registration.enabled ? 'on' : '')}>{registration.enabled ? '已启用' : '已停用'}</span></div>
<div className="mcp-source"><div><span>可执行文件</span><code>{registration.launch.executable.path}</code><small><Fingerprint size={12} /> SHA256 {registration.launch.executable.sha256.slice(0, 16)} · {registration.launch.executable.bytes.toLocaleString()} B</small></div>
{registration.launch.entry && <div><span>脚本入口</span><code>{registration.launch.entry.path}</code><small>SHA256 {registration.launch.entry.sha256.slice(0, 16)} · {registration.launch.entry.bytes.toLocaleString()} B</small></div>}
<span>{view.executionMode === 'unrestricted' ? '开放执行 · 不设请求超时' : '请求上限 ' + registration.timeoutMs.toLocaleString() + ' ms'}</span></div>
{registration.reason && <p className="mcp-warning">{registration.reason}</p>}
{registration.contract && <div className="mcp-contract-line"><Check size={13} />实际契约 SHA256 {registration.contract.sha256.slice(0, 16)} · 发现 {registration.tools.length} 项工具</div>}
{registration.contract && <div className="mcp-tool-list"><div className="mcp-tool-heading"><strong>允许模型请求的工具</strong><span>已选择 {chosen.length}{view.limits.allowedTools === null ? ' · 数量不限' : ' / ' + view.limits.allowedTools}</span></div>
{registration.tools.map(tool => <label className={'mcp-tool-option ' + (tool.unsupported ? 'unsupported' : '')} key={tool.name}>
<input type="checkbox" checked={chosen.includes(tool.name)} disabled={locked || !!tool.unsupported || registration.status !== 'verified' || view.limits.allowedTools !== null && chosen.length >= (view.limits.allowedTools ?? 12) && !chosen.includes(tool.name)} onChange={event => setSelectedTools(previous => ({ ...previous,
[registration.id]: event.target.checked ? [...chosen, tool.name] : chosen.filter(name => name !== tool.name) }))} />
<span><strong>{tool.name}</strong>{tool.unsupported && <em>参数契约不受支持</em>}<small>{tool.description || '未提供用途说明'}</small>
<details><summary>查看参数契约</summary><pre>{JSON.stringify(tool.inputSchema, null, 2)}</pre>{tool.unsupported && <code>{tool.unsupported}</code>}</details></span>
</label>)}
{!registration.tools.length && <p className="mcp-empty">实际服务没有声明可发现工具。</p>}
</div>}
<div className="mcp-controls"><button type="button" className="button secondary" disabled={locked || !session || registration.status === 'changed'} onClick={() => { setRequestError(''); setProbeTarget(registration); }}><PlugZap size={14} />实际探测</button>
{registration.contract && <button type="button" className={registration.enabled ? 'button secondary' : 'button primary'} disabled={locked || registration.status !== 'verified' || !!selectedTools[registration.id]?.length && !registration.contract} onClick={() => void saveTools(registration)}><Power size={14} />{chosen.length ? '保存并启用所选工具' : '停用 MCP'}</button>}
{registration.enabled && <button type="button" className="button secondary" disabled={locked} onClick={() => void disable(registration)}><Power size={14} />立即停用</button>}
{busyJobs && session && <button type="button" className="button danger" disabled={working} onClick={() => void stop()}><AlertTriangle size={14} />停止当前 MCP 操作</button>}</div>
</article>;
})}</div> : view && <div className="mcp-empty"><PlugZap size={24} /><strong>尚未登记项目 MCP</strong><p>只登记你已审查的本地可执行文件。程序和 Node 入口会在探测及启用前重新计算 SHA256。</p></div>}
{!view && !error && <p className="mcp-empty"><LoaderCircle size={18} className="spin" />正在读取项目注册</p>}
<form className="mcp-register" onSubmit={register}>
<div className="mcp-register-heading"><h4><Plus size={16} />登记本地 MCP</h4><span>绝对路径 · 默认停用 · {view?.limits.registrations === null ? '登记数量不限' : '最多 ' + (view?.limits.registrations ?? 16) + ' 项'}</span></div>
<div className="mcp-form-grid"><label>显示名称<input required value={draft.name} maxLength={100} onChange={event => setDraft({ ...draft, name: event.target.value })} placeholder="例如:项目只读检索" /></label>
<label>{view?.executionMode === 'unrestricted' ? '手动限制模式的超时(毫秒)' : '请求超时(毫秒)'}<input required type="number" min={500} max={45000} step={500} value={draft.timeoutMs} onChange={event => setDraft({ ...draft, timeoutMs: Number(event.target.value) })} /></label>
<label className="mcp-full">可执行文件绝对路径<input required value={draft.executable} onChange={event => setDraft({ ...draft, executable: event.target.value })} placeholder="C:\Tools\my-mcp.exe 或当前 Node.js 可执行文件" /></label>
<label className="mcp-full">Node 脚本入口(可选)<input value={draft.entry} onChange={event => setDraft({ ...draft, entry: event.target.value })} placeholder="仅接受 .js、.mjs、.cjs;留空表示直接启动可执行文件" /></label></div>
<footer><span>仅保留系统路径与临时目录环境,不传入模型 Key;不安装脚本、不使用 shell。</span><button type="submit" className="button primary" disabled={locked || !draft.name.trim() || !draft.executable.trim()}>{working ? <LoaderCircle size={14} className="spin" /> : <Plus size={14} />}登记后保持停用</button></footer>
</form>
{session && <McpJobHistory session={session} jobs={jobs} total={history.total} hasMore={history.hasMore} loading={history.loading} loadMore={history.loadMore} busy={locked} onSession={onSession} onError={onError} />}
{!session && <p className="mcp-empty">选择或创建一个任务会话后,可以对已登记程序执行探测。</p>}
{probeTarget && <Modal title="启动 MCP 实际探测" description="工作台将启动该登记程序、核对固定协议并读取实际工具 schema,不调用工具或模型。" onClose={() => { setProbeTarget(null); setRequestError(''); }}>
<div className="mcp-probe-summary"><strong>{probeTarget.name}</strong><code>{probeTarget.launch.executable.path}</code>{probeTarget.launch.entry && <code>{probeTarget.launch.entry.path}</code>}
<span>程序会以当前 Windows 用户权限运行;独立进程不等于 OS 沙箱。探测期间不会继承工作台模型凭据。</span></div>
{requestError && <p className="mcp-alert" role="alert"><CircleAlert size={15} />{requestError}</p>}
<div className="modal-actions"><button type="button" className="button secondary" disabled={working} onClick={() => setProbeTarget(null)}>取消</button><button type="button" className="button primary" disabled={working || busy} onClick={() => void probe()}>{working ? <LoaderCircle size={14} className="spin" /> : <PlugZap size={14} />}确认启动并探测</button></div>
</Modal>}
</section>;
}