mirror of
https://github.com/ThearchyHelios/AgentLab.git
synced 2026-11-23 18:21:58 +00:00
1361 lines
67 KiB
TypeScript
1361 lines
67 KiB
TypeScript
import { useEffect, useRef, useState } from 'react'
|
||
import { useNavigate, useParams, useSearchParams } from 'react-router-dom'
|
||
import { AlertTriangle, Play, Plug, Plus, RefreshCw, Search, ShieldCheck, Terminal, Wand2, Wrench } from 'lucide-react'
|
||
import clsx from 'clsx'
|
||
import { api, ApiError } from '../api/client'
|
||
import { useCatalog, useOnReconnect } from '../store/catalog'
|
||
import {
|
||
confirmDialog, deferDelete, DeleteButton, EmptyState, ErrorState, Field, HealthPill, JsonInput, Kbd, Modal,
|
||
PageHeader, SectionBar, Skeleton, Spinner, StatusBadge, TabPanel, Tabs, toast, useRadioGroup, useTabRoute, withoutDeferred,
|
||
} from '../components/ui'
|
||
import { humanizeError } from '../lib/errors'
|
||
import { formatDuration } from '../lib/format'
|
||
import { customToolEditPath } from '../lib/explain'
|
||
import { checkHealth, forgetHealth, healthFromServer, useHealth } from '../lib/health'
|
||
import type { HealthRecord } from '../lib/health'
|
||
import { ariaShortcut, matchShortcut } from '../lib/keys'
|
||
import { workflowList, workflowsMentioning } from '../lib/mentions'
|
||
import {
|
||
CAPABILITY_TEXT, ENDPOINT_TEXT, MCP_AUTH_TEXT, TOOL_ENDPOINT_TEXT, TOOL_REHEARSAL_TEXT, TOOL_TRUST_HINT, TOOL_TRUST_LABEL,
|
||
TOOL_TRUST_TEXT, TOOL_TRUST_VALUES,
|
||
} from '../lib/terms'
|
||
import { useAtLeast } from '../store/auth'
|
||
import type { EndpointRow } from '../typesApp'
|
||
import { CapabilitiesTab } from './tools/CapabilitiesTab'
|
||
import { EndpointsTab } from './tools/EndpointsTab'
|
||
import { useRunClock } from '../run/useRunClock'
|
||
import type { ToolInfo, ToolTrust } from '../types'
|
||
|
||
// 提到模块级:tab 名同时是 URL 的最后一段,两处各写一份迟早对不上
|
||
const TABS = [
|
||
// key 是 URL 的一段。叫 tools 的话地址会变成 /tools/tools/<id>,
|
||
// 读起来像敲重了。这个 URL 今天才上线,改的代价最小
|
||
{ key: 'library', label: '工具库' },
|
||
{ key: 'sandbox', label: '沙箱试验台' },
|
||
{ key: 'custom', label: '自定义工具' },
|
||
{ key: 'mcp', label: 'MCP 接入' },
|
||
// 应用平台(A6):能力登记和端点。/tools/capabilities/<能力名> 直接打开那一个的治理设置
|
||
{ key: 'capabilities', label: CAPABILITY_TEXT.tab },
|
||
{ key: 'endpoints', label: ENDPOINT_TEXT.tab },
|
||
]
|
||
|
||
export function ToolsPage() {
|
||
const [tab, setTab] = useTabRoute(TABS.map((t) => t.key), 'library')
|
||
return (
|
||
<div className="flex h-full flex-col">
|
||
<PageHeader
|
||
icon={<Wrench size={13} />}
|
||
title="工具"
|
||
subtitle="无需搭建工作流即可单独执行工具;接入自定义工具和 MCP 服务后,可在节点中直接使用;能力和端点在这里治理"
|
||
/>
|
||
<Tabs tabs={TABS} active={tab} onChange={setTab} label="工具" idPrefix="tools" />
|
||
<TabPanel idPrefix="tools" tabKey={tab} className="min-h-0 flex-1 overflow-y-auto">
|
||
{tab === 'library' && <ToolLibrary />}
|
||
{tab === 'sandbox' && <SandboxLab />}
|
||
{tab === 'custom' && <CustomTools />}
|
||
{tab === 'mcp' && <McpServers />}
|
||
{tab === 'capabilities' && <CapabilitiesTab />}
|
||
{tab === 'endpoints' && <EndpointsTab />}
|
||
</TabPanel>
|
||
</div>
|
||
)
|
||
}
|
||
|
||
// -------------------------------------------------------------------------
|
||
|
||
/**
|
||
* 按参数 Schema 拼一份示例参数:有 default / examples / enum 用它们,否则按类型给
|
||
* 空值。all=false 只拼必填项——选中工具时先填好骨架,比空的 {} 少敲一半。
|
||
*/
|
||
export function exampleArgs(schema: any, all = false): Record<string, any> {
|
||
const props: Record<string, any> = schema?.properties ?? {}
|
||
const required: string[] = schema?.required ?? []
|
||
const out: Record<string, any> = {}
|
||
for (const [key, spec] of Object.entries(props)) {
|
||
if (!all && !required.includes(key) && spec?.default === undefined) continue
|
||
out[key] = sampleOf(spec)
|
||
}
|
||
return out
|
||
}
|
||
|
||
function sampleOf(spec: any): any {
|
||
if (spec?.default !== undefined) return spec.default
|
||
if (Array.isArray(spec?.examples) && spec.examples.length) return spec.examples[0]
|
||
if (Array.isArray(spec?.enum) && spec.enum.length) return spec.enum[0]
|
||
const type = Array.isArray(spec?.type) ? spec.type[0] : spec?.type
|
||
switch (type) {
|
||
case 'integer': case 'number': return 0
|
||
case 'boolean': return false
|
||
case 'array': return []
|
||
case 'object': return spec?.properties ? exampleArgs(spec, true) : {}
|
||
default: return ''
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 在工具库里直接执行时,它的副作用落在哪里。说实话:内置工具有围栏,外接的没有;写外部系统的能力在这里只演练
|
||
* (服务端给的 write_rehearsal,和执行接口同一个判断),不说「请求会实际发出」
|
||
*/
|
||
function sideEffectNote(tool: ToolInfo): string {
|
||
if (tool.write_rehearsal) return TOOL_REHEARSAL_TEXT.library
|
||
if (tool.source !== 'builtin') return '自定义工具和 MCP 工具的副作用由工具自身决定,此处无法拦截:请求会实际发出,并可能修改外部系统。'
|
||
if (tool.category === '文件') return '文件读写限定在工作目录内,无法访问其他位置。'
|
||
if (tool.category === '网络') return '内网、回环和云元数据地址会被拦截,公网请求会实际发出。'
|
||
if (tool.category === '沙箱') return '代码在沙箱中执行,受沙箱的超时、内存和联网限制。'
|
||
return ''
|
||
}
|
||
|
||
function ToolLibrary() {
|
||
const tools = useCatalog((s) => s.tools)
|
||
const { id } = useParams()
|
||
const navigate = useNavigate()
|
||
const [args, setArgs] = useState<any>({})
|
||
const [result, setResult] = useState<any>(null)
|
||
const [busy, setBusy] = useState(false)
|
||
const [query, setQuery] = useState('')
|
||
const since = useRef(0)
|
||
const clock = useRunClock(busy)
|
||
|
||
// 选中哪个由地址说了算:这样一个工具的参数说明可以直接发给别人
|
||
const picked = tools.find((t) => t.id === id) ?? null
|
||
useEffect(() => {
|
||
setArgs(picked ? exampleArgs(picked.schema) : {})
|
||
setResult(null)
|
||
}, [picked?.id])
|
||
|
||
const run = async () => {
|
||
if (!picked || busy) return
|
||
since.current = Date.now()
|
||
setBusy(true)
|
||
setResult(null)
|
||
try {
|
||
let out: any
|
||
try {
|
||
out = await api.tools.run(picked.id, args ?? {})
|
||
} catch (e) {
|
||
// 有副作用的工具,后端先回 409 说明它要做什么;人看过、点了确认才真跑。
|
||
// 工作流里的「运行时需审批」是另一回事,这里不经审批关卡
|
||
if (!(e instanceof ApiError) || e.status !== 409) throw e
|
||
setBusy(false)
|
||
const ok = await confirmDialog({
|
||
title: `执行 ${picked.name}?`,
|
||
body: e.message,
|
||
consequences: [sideEffectNote(picked)].filter(Boolean),
|
||
confirmLabel: '确认执行',
|
||
danger: true,
|
||
})
|
||
if (!ok) return
|
||
since.current = Date.now()
|
||
setBusy(true)
|
||
out = await api.tools.run(picked.id, args ?? {}, { confirm: true })
|
||
}
|
||
setResult(out)
|
||
} catch (e) {
|
||
setResult({ ok: false, thrown: e })
|
||
} finally {
|
||
setBusy(false)
|
||
}
|
||
}
|
||
|
||
const needle = query.trim().toLowerCase()
|
||
const shown = tools.filter(
|
||
(t) => !needle || [t.name, t.description, t.category].some((s) => s?.toLowerCase().includes(needle)),
|
||
)
|
||
const groups = [...new Set(shown.map((t) => t.category))]
|
||
const props = Object.entries((picked?.schema?.properties ?? {}) as Record<string, any>)
|
||
|
||
return (
|
||
<div className="flex h-full">
|
||
<div className="flex w-[320px] shrink-0 flex-col border-r">
|
||
<div className="flex items-center gap-2 border-b px-3 py-2">
|
||
<Search size={12} className="text-faint" aria-hidden />
|
||
<input className="min-w-0 flex-1 bg-transparent text-xs outline-none placeholder:text-faint"
|
||
placeholder={`搜索 ${tools.length} 个工具…`} aria-label="搜索工具" value={query}
|
||
onChange={(e) => setQuery(e.target.value)} />
|
||
</div>
|
||
<nav className="flex-1 overflow-y-auto p-2" aria-label="工具列表">
|
||
{groups.map((g) => (
|
||
<div key={g} className="mb-3">
|
||
<div className="mb-1 px-1.5 text-2xs font-semibold tracking-wide text-faint">{g}</div>
|
||
{shown.filter((t) => t.category === g).map((t) => {
|
||
const on = picked?.id === t.id
|
||
return (
|
||
<button
|
||
key={t.id}
|
||
// MCP 工具的 id 是 mcp:服务名/工具名,带斜杠:不转义就对不上 /tools/:tab/:id,落到 404
|
||
onClick={() => navigate(`/tools/library/${encodeURIComponent(t.id)}`)}
|
||
aria-current={on ? 'true' : undefined}
|
||
className={clsx(
|
||
'relative w-full rounded-md px-2 py-1.5 text-left hover:bg-hover',
|
||
on && 'bg-hover',
|
||
)}
|
||
>
|
||
{on && <span className="absolute inset-y-1.5 left-0 w-0.5 rounded bg-[var(--accent)]" aria-hidden />}
|
||
<div className="flex items-center gap-1.5">
|
||
<span className="mono truncate text-xs">{t.name}</span>
|
||
{t.problem ? <ProblemChip problem={t.problem} /> : <ApprovalTag tool={t} />}
|
||
</div>
|
||
<div className="truncate text-2xs text-faint">{t.description}</div>
|
||
</button>
|
||
)
|
||
})}
|
||
</div>
|
||
))}
|
||
{!shown.length && (
|
||
<EmptyState offline={false} icon={<Wrench size={20} />} title="没有匹配的工具"
|
||
action={<button className="btn btn-sm" onClick={() => setQuery('')}>清空搜索</button>} />
|
||
)}
|
||
</nav>
|
||
</div>
|
||
|
||
<div className="min-w-0 flex-1 overflow-y-auto p-4">
|
||
{!picked && (
|
||
<EmptyState icon={<Wrench size={22} />} title="选择一个工具"
|
||
body="无需搭建工作流即可单独执行工具,验证参数和返回格式。" />
|
||
)}
|
||
{picked && (
|
||
<div className="max-w-2xl">
|
||
<div className="mb-1 flex flex-wrap items-center gap-2">
|
||
<span className="mono text-sm font-semibold">{picked.name}</span>
|
||
<span className="chip">{({ builtin: '内置', custom: '自定义', mcp: 'MCP' } as Record<string, string>)[picked.source] ?? picked.source}</span>
|
||
<ApprovalTag tool={picked} long />
|
||
</div>
|
||
<p className="mb-3 text-xs leading-relaxed text-dim">{picked.description}</p>
|
||
|
||
{hasTrust(picked) && (
|
||
<div className="mb-3 rounded-lg border bg-panel px-2.5 py-2" data-trust-block>
|
||
<div className="flex flex-wrap items-center gap-2">
|
||
<span className="text-xs font-medium">{TOOL_TRUST_TEXT.title}</span>
|
||
<TrustControl tool={picked} />
|
||
</div>
|
||
<p className="mt-1 text-2xs leading-relaxed text-faint">{TOOL_TRUST_TEXT.explain}</p>
|
||
</div>
|
||
)}
|
||
|
||
{picked.problem && (
|
||
<div role="alert" className="mb-3 flex items-start gap-2 rounded-lg border px-2.5 py-2 text-xs leading-relaxed" data-tool-problem-detail
|
||
style={{ borderColor: 'color-mix(in srgb, var(--st-failed) 40%, var(--border))', background: 'var(--st-failed-soft)' }}>
|
||
<StatusBadge status="failed" size={13} decorative className="mt-0.5 shrink-0" />
|
||
<span className="min-w-0 flex-1">
|
||
<span className="font-medium" style={{ color: 'var(--st-failed)' }}>{picked.problem}</span>
|
||
<span className="block text-dim">绑定该工具的节点运行时一定失败。请先修正参数定义,再回到此处执行。</span>
|
||
</span>
|
||
<button className="btn btn-sm shrink-0" onClick={() => navigate(customToolEditPath(picked.name))}>去改参数定义</button>
|
||
</div>
|
||
)}
|
||
|
||
{picked.dangerous && (picked.write_rehearsal ? (
|
||
// 写入能力:执行不先确认(演练没有副作用)、也不真的发出,提示条和结果的「演练」同一个颜色
|
||
<div className="mb-3 flex gap-2 rounded-lg border px-2.5 py-2 text-xs leading-relaxed" data-tool-side-effect="rehearsal"
|
||
style={{ borderColor: 'color-mix(in srgb, var(--st-waiting) 40%, var(--border))', background: 'var(--st-waiting-soft)' }}>
|
||
<StatusBadge status="waiting" size={13} decorative className="mt-0.5 shrink-0" />
|
||
<span>{sideEffectNote(picked)}</span>
|
||
</div>
|
||
) : (
|
||
<div className="mb-3 flex gap-2 rounded-lg border px-2.5 py-2 text-xs leading-relaxed" data-tool-side-effect="send"
|
||
style={{ borderColor: 'color-mix(in srgb, var(--warn) 40%, var(--border))', background: 'color-mix(in srgb, var(--warn) 7%, transparent)' }}>
|
||
<AlertTriangle size={13} className="mt-0.5 shrink-0 text-[var(--warn)]" aria-hidden />
|
||
<span>
|
||
此处直接执行,不经审批:执行前会先说明具体操作,确认后才会执行。{sideEffectNote(picked)}
|
||
</span>
|
||
</div>
|
||
))}
|
||
|
||
<div className="mb-1 flex items-center gap-2">
|
||
<label className="label !mb-0" htmlFor="tool-args">参数</label>
|
||
{props.length > 0 && (
|
||
<button className="btn btn-xs ml-auto" onClick={() => setArgs(exampleArgs(picked.schema, true))}
|
||
title="按参数说明把每一项都填上示例值">
|
||
<Wand2 size={11} aria-hidden /> 填入全部参数
|
||
</button>
|
||
)}
|
||
</div>
|
||
<JsonInput key={picked.id} id="tool-args" value={args} onChange={setArgs} rows={6} placeholder="{}" />
|
||
|
||
{props.length > 0 && (
|
||
<div className="mt-2 overflow-hidden rounded-lg border bg-panel">
|
||
<div className="border-b px-2.5 py-1 text-2xs font-semibold text-faint">参数说明</div>
|
||
{props.map(([key, spec]) => (
|
||
<div key={key} className="flex gap-2 border-b border-[var(--hairline)] px-2.5 py-1 text-xs last:border-0">
|
||
<code className="mono w-32 shrink-0 truncate text-[var(--accent)]">{key}</code>
|
||
<span className="mono w-16 shrink-0 text-2xs leading-5 text-faint">{spec.type}</span>
|
||
<span className="min-w-0 flex-1 text-dim">
|
||
{spec.description ?? ''}
|
||
{(picked.schema.required ?? []).includes(key) && (
|
||
<span className="ml-1 text-[var(--err)]">必填</span>
|
||
)}
|
||
</span>
|
||
</div>
|
||
))}
|
||
</div>
|
||
)}
|
||
|
||
<button className="btn btn-primary mt-3 tnum" onClick={() => void run()} disabled={busy}>
|
||
{busy ? <><Spinner /> 执行中 {formatDuration(clock - since.current)}</> : <><Play size={12} aria-hidden /> 执行</>}
|
||
</button>
|
||
|
||
{result && <ToolResult result={result} />}
|
||
</div>
|
||
)}
|
||
</div>
|
||
</div>
|
||
)
|
||
}
|
||
|
||
/**
|
||
* 自定义工具存着的参数定义写坏了(后端 schema_problem)。绑了它的节点运行时一定失败,
|
||
* 所以是醒目的失败色、带剪影,完整的那句放 title 和读屏名字里
|
||
*/
|
||
function ProblemChip({ problem }: { problem: string }) {
|
||
return (
|
||
<span className="chip shrink-0" data-tool-problem title={problem} aria-label={`参数定义有误:${problem}`}
|
||
style={{ color: 'var(--st-failed)', borderColor: 'color-mix(in srgb, var(--st-failed) 45%, transparent)', background: 'var(--st-failed-soft)' }}>
|
||
<StatusBadge status="failed" size={10} decorative />参数定义有误
|
||
</span>
|
||
)
|
||
}
|
||
|
||
/**
|
||
* 「运行时需审批」只给真会停下来等人的工具打(后端的 runtime_approval)。
|
||
*
|
||
* MCP / 自定义工具按信任档说:等审批挂「运行时需审批」,门控把关挂「门控把关」,
|
||
* 始终允许什么都不挂——它就是不会停。老后端没有信任档,那时审批关卡认不出它们,
|
||
* 就明说「运行时不审批」:以前它们也挂着「需确认」,标签说的不是实话,给人虚假的安全感。
|
||
*/
|
||
function ApprovalTag({ tool, long = false }: { tool: ToolInfo; long?: boolean }) {
|
||
const trust = tool.source !== 'builtin' ? tool.trust : undefined
|
||
if (trust === 'always') return null
|
||
if (trust === 'gated') {
|
||
return (
|
||
<span className="chip shrink-0" title={TOOL_TRUST_TEXT.badgeGatedHint} data-trust-badge="gated">
|
||
<ShieldCheck size={10} aria-hidden />{TOOL_TRUST_TEXT.badgeGated}
|
||
</span>
|
||
)
|
||
}
|
||
const needs = trust === 'ask' || (tool.runtime_approval ?? (tool.source === 'builtin' && tool.dangerous))
|
||
if (needs) {
|
||
return (
|
||
<span className="chip shrink-0" style={{ color: 'var(--st-waiting)', borderColor: 'color-mix(in srgb, var(--st-waiting) 40%, transparent)' }}
|
||
data-trust-badge={trust ? 'ask' : undefined}
|
||
title="工作流运行到该工具时会暂停,等待人工审批(审批策略为「危险工具」时)。在工具库中直接执行不经审批。">
|
||
<StatusBadge status="waiting" size={10} decorative />{TOOL_TRUST_TEXT.badgeAsk}
|
||
</span>
|
||
)
|
||
}
|
||
if (tool.source !== 'builtin') {
|
||
return (
|
||
<span className="chip shrink-0 border-dashed"
|
||
title="自定义工具和 MCP 工具在工作流中执行时不会暂停等待审批:审批机制目前无法识别这类工具。如有副作用,请在节点上另行控制。">
|
||
运行时不审批{long ? ' · 副作用需自行把控' : ''}
|
||
</span>
|
||
)
|
||
}
|
||
return null
|
||
}
|
||
|
||
/** 后端给了信任档的才显示三选一:内置工具没有,老后端也没有 */
|
||
const hasTrust = (tool: ToolInfo | undefined | null): tool is ToolInfo & { trust: ToolTrust } =>
|
||
!!tool && tool.source !== 'builtin' && typeof tool.trust === 'string'
|
||
|
||
/** MCP 工具的 name 只是裸名(search),同名的可能来自几台服务:说全称 */
|
||
const toolLabel = (tool: ToolInfo) => (tool.source === 'mcp' ? tool.id : tool.name)
|
||
|
||
/** 同一个工具最近一次改档的序号:只有最后那次请求的结果算数 */
|
||
const trustSeq = new Map<string, number>()
|
||
|
||
/**
|
||
* 改信任档:先改 catalog 里的这一项(工具库、自定义工具、MCP 三处读的都是它),再 PUT;
|
||
* 失败就改回去,并说原因。连点几档时,前面那次请求的失败不回退:界面上已经是后来
|
||
* 选的那一档,退回去反而和最后那次请求对不上
|
||
*/
|
||
async function setToolTrust(tool: ToolInfo, next: ToolTrust) {
|
||
const key = tool.trust_key ?? tool.id
|
||
if (tool.trust === next) return
|
||
const prev = { trust: tool.trust, runtime_approval: tool.runtime_approval }
|
||
const seq = (trustSeq.get(key) ?? 0) + 1
|
||
trustSeq.set(key, seq)
|
||
const patch = (fields: Partial<ToolInfo>) => useCatalog.setState((s) => ({
|
||
tools: s.tools.map((t) => ((t.trust_key ?? t.id) === key && t.source === tool.source ? { ...t, ...fields } : t)),
|
||
}))
|
||
patch({ trust: next, runtime_approval: next !== 'always' })
|
||
try {
|
||
const out = await api.tools.setTrust(key, next)
|
||
// 后端可能把值规范过(比如 key 在表里已经删了):以它回的为准
|
||
if (trustSeq.get(key) === seq && out?.trust && out.trust !== next && TOOL_TRUST_VALUES.includes(out.trust)) {
|
||
patch({ trust: out.trust, runtime_approval: out.trust !== 'always' })
|
||
}
|
||
} catch (e) {
|
||
if (trustSeq.get(key) !== seq) return
|
||
patch(prev)
|
||
const h = humanizeError(e)
|
||
toast.error(`${TOOL_TRUST_TEXT.saveFailed(toolLabel(tool))}:${h.reason ? `${h.title},${h.reason}` : h.title}`,
|
||
{ detail: h.raw })
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 信任档三选一。整组一个 Tab 位、方向键切换(useRadioGroup),选中即保存:
|
||
* 这是偏好不是表单,和主题一样不设「保存」按钮。没有信任档的(内置、老后端)不画
|
||
*/
|
||
function TrustControl({ tool }: { tool: ToolInfo | null | undefined }) {
|
||
const radio = useRadioGroup(TOOL_TRUST_VALUES, tool?.trust, (v) => { if (tool) void setToolTrust(tool, v) })
|
||
if (!hasTrust(tool)) return null
|
||
return (
|
||
<span role="radiogroup" aria-label={TOOL_TRUST_TEXT.groupLabel(toolLabel(tool))}
|
||
className="inline-flex shrink-0 whitespace-nowrap rounded-md border p-px"
|
||
data-trust-control={tool.trust_key ?? tool.id} data-trust={tool.trust}>
|
||
{TOOL_TRUST_VALUES.map((v) => (
|
||
<button key={v} type="button" {...radio(v)} title={TOOL_TRUST_HINT[v]}
|
||
className={clsx('rounded px-1.5 text-2xs leading-5 transition-colors',
|
||
v === tool.trust ? 'bg-accent-soft text-fg' : 'text-faint hover:text-dim')}
|
||
onClick={() => void setToolTrust(tool, v)}>
|
||
{TOOL_TRUST_LABEL[v]}
|
||
</button>
|
||
))}
|
||
</span>
|
||
)
|
||
}
|
||
|
||
/**
|
||
* 执行 / 试跑的结果。
|
||
*
|
||
* note:后端把拼错的参数名按唯一候选纠正了(「参数名 cuont 不存在,已按唯一候选
|
||
* count 执行」)。跑是跑通了,但人会照着这份参数去配工作流,所以跟在结果下面
|
||
* 用 warn 写出来,不能只当成功。
|
||
*
|
||
* rehearsal:写入能力在这里只演练、不发送(服务端 tools/custom.held_write),结果是将要发送的请求,不说「成功」。
|
||
* HTTP 工具对方回了非 2xx 的,服务端已经按失败交回(写明状态码),这里照常画失败
|
||
*/
|
||
function ToolResult({ result, stale = false }: { result: any; stale?: boolean }) {
|
||
const failed = result.ok === false
|
||
const rehearsal = !failed && result.rehearsal === true
|
||
// 新结果常落在弹窗或详情区的可视范围以外(试跑区在编辑框最底下),note 的提醒不滚就
|
||
// 看不见——而它就是要人在抄参数之前看到。每来一份新结果带进视野一次;不加 smooth,
|
||
// reduced-motion 下也不会有滚动动画
|
||
const ref = useRef<HTMLDivElement>(null)
|
||
useEffect(() => { ref.current?.scrollIntoView({ block: 'nearest' }) }, [result])
|
||
return (
|
||
<div ref={ref} className={clsx('mt-3', stale && 'opacity-60')} data-tool-result={failed ? 'fail' : rehearsal ? 'rehearsal' : 'ok'}>
|
||
<div className="mb-1 flex items-center gap-1.5 text-xs">
|
||
<StatusBadge status={failed ? 'failed' : rehearsal ? 'waiting' : 'done'} size={12} decorative />
|
||
<span style={{ color: failed ? 'var(--err)' : rehearsal ? 'var(--st-waiting)' : 'var(--text-dim)' }}>
|
||
{failed ? '失败' : rehearsal ? TOOL_REHEARSAL_TEXT.badge : '成功'}
|
||
</span>
|
||
{result.duration_ms != null && <span className="tnum text-faint">· {formatDuration(result.duration_ms)}</span>}
|
||
{stale && <span className="text-faint">· 配置或参数已修改,这是修改前的结果</span>}
|
||
</div>
|
||
{result.note && (
|
||
<div className="mb-1.5 flex items-start gap-1.5 rounded-md border px-2 py-1.5 text-xs leading-relaxed" data-tool-note
|
||
style={{ borderColor: 'color-mix(in srgb, var(--warn) 40%, var(--border))', background: 'color-mix(in srgb, var(--warn) 7%, transparent)' }}>
|
||
<AlertTriangle size={12} className="mt-0.5 shrink-0 text-[var(--warn)]" aria-hidden />
|
||
<span>
|
||
<span className="text-[var(--warn)]">{String(result.note).replace(/[。.]\s*$/, '')}</span>
|
||
<span className="text-dim">。本次已按纠正后的名称执行;在工作流中使用前,请先修正参数名称</span>
|
||
</span>
|
||
</div>
|
||
)}
|
||
{failed ? (
|
||
<ErrorState compact error={result.thrown ?? result} />
|
||
) : rehearsal ? (
|
||
<Rehearsal value={result.result} />
|
||
) : (
|
||
<pre className="mono max-h-96 overflow-auto whitespace-pre-wrap break-words rounded-lg border bg-panel p-2.5 text-xs leading-relaxed">
|
||
{typeof result.result === 'string' ? result.result : JSON.stringify(result.result, null, 2)}
|
||
</pre>
|
||
)}
|
||
</div>
|
||
)
|
||
}
|
||
|
||
/** 演练回执:将要发送的方法和地址、环境、请求头的名字、请求体;拼不出请求的(Python、MCP、数据源)没有执行,列这次的参数 */
|
||
function Rehearsal({ value }: { value: any }) {
|
||
const req = value?.request
|
||
const T = TOOL_REHEARSAL_TEXT
|
||
const json = (v: unknown) => (v == null ? T.none : JSON.stringify(v, null, 2))
|
||
return (
|
||
<div className="space-y-1.5 rounded-lg border bg-panel p-2.5 text-xs" data-tool-rehearsal="">
|
||
<p className="text-2xs leading-relaxed text-dim">{req ? T.hint : T.hintArgs}</p>
|
||
{req ? (
|
||
<dl className="grid grid-cols-[4.5rem_1fr] gap-x-2 gap-y-1">
|
||
<dt className="text-faint">{T.request}</dt>
|
||
<dd className="mono min-w-0 break-all" data-tool-rehearsal-request="">{req.method} {req.url}</dd>
|
||
{value.environment && (
|
||
<>
|
||
<dt className="text-faint">{T.environment}</dt>
|
||
<dd>{ENDPOINT_TEXT.envs[value.environment] ?? value.environment}{value.endpoint ? ` · ${value.endpoint}` : ''}</dd>
|
||
</>
|
||
)}
|
||
<dt className="text-faint">{T.headers}</dt>
|
||
<dd className="mono min-w-0 break-all">{req.headers?.length ? req.headers.join('、') : T.none}</dd>
|
||
<dt className="text-faint">{T.body}</dt>
|
||
<dd className="min-w-0">
|
||
<pre className="mono max-h-60 overflow-auto whitespace-pre-wrap break-words">{json(req.body)}</pre>
|
||
</dd>
|
||
</dl>
|
||
) : (
|
||
<pre className="mono max-h-60 overflow-auto whitespace-pre-wrap break-words">{json(value?.args)}</pre>
|
||
)}
|
||
</div>
|
||
)
|
||
}
|
||
|
||
// -------------------------------------------------------------------------
|
||
|
||
function SandboxLab() {
|
||
const [code, setCode] = useState(
|
||
'import sys, platform\nprint("Python", sys.version.split()[0], "on", platform.machine())\nprint(sum(range(101)))',
|
||
)
|
||
const [language, setLanguage] = useState('python')
|
||
const [network, setNetwork] = useState(false)
|
||
const [timeout_, setTimeout_] = useState(30)
|
||
const [result, setResult] = useState<any>(null)
|
||
const [busy, setBusy] = useState(false)
|
||
const [health, setHealth] = useState<any>(null)
|
||
const since = useRef(0)
|
||
const clock = useRunClock(busy)
|
||
// 结果头要用发出请求时的超时,不是之后又改过的输入框
|
||
const sentTimeout = useRef(timeout_)
|
||
|
||
const loadHealth = () => api.sandbox.health().then(setHealth, () => {})
|
||
useEffect(() => { void loadHealth() }, [])
|
||
useOnReconnect(loadHealth)
|
||
|
||
const run = async () => {
|
||
if (busy) return
|
||
since.current = Date.now()
|
||
sentTimeout.current = timeout_
|
||
setBusy(true)
|
||
setResult(null)
|
||
try {
|
||
setResult(await api.sandbox.exec({ code, language, network, timeout: timeout_ }))
|
||
} catch (e) {
|
||
setResult({ ok: false, thrown: e })
|
||
} finally {
|
||
setBusy(false)
|
||
}
|
||
}
|
||
|
||
// 没有退出码就是请求没到沙箱,别拼出「exit undefined」
|
||
const headline = !result ? '' : result.thrown ? '请求未送达沙箱'
|
||
: result.ok ? '成功'
|
||
: result.timed_out ? `超过 ${sentTimeout.current} 秒被终止`
|
||
: result.exit_code == null ? '请求未送达沙箱'
|
||
: `失败 · 退出码 ${result.exit_code}`
|
||
|
||
return (
|
||
<div className="mx-auto max-w-4xl p-4">
|
||
{health && (
|
||
<div className="mb-3 flex flex-wrap items-center gap-2 rounded-lg border bg-panel px-3 py-2 text-xs">
|
||
<Terminal size={12} className="text-dim" aria-hidden />
|
||
<span>沙箱 <span className="mono font-medium">{health.backend}</span></span>
|
||
<span className="inline-flex items-center gap-1" style={{ color: health.available ? 'var(--text-dim)' : 'var(--err)' }}>
|
||
<StatusBadge status={health.available ? 'done' : 'failed'} size={11} decorative />
|
||
{health.available ? '可用' : '不可用'}
|
||
</span>
|
||
<span className="min-w-0 truncate text-faint" title={health.selected_because}>· {health.selected_because}</span>
|
||
{health.warning && <span className="w-full text-2xs text-[var(--warn)]">{health.warning}</span>}
|
||
</div>
|
||
)}
|
||
|
||
<div className="mb-2 flex flex-wrap items-center gap-3">
|
||
<select className="field w-28" value={language} aria-label="语言" onChange={(e) => setLanguage(e.target.value)}>
|
||
<option value="python">Python</option>
|
||
<option value="bash">Bash</option>
|
||
<option value="node">Node.js</option>
|
||
</select>
|
||
<label className="flex items-center gap-1.5 text-xs">
|
||
超时
|
||
<input className="field w-16 tnum" type="number" min={1} value={timeout_}
|
||
onChange={(e) => setTimeout_(Math.max(1, Number(e.target.value) || 1))} />
|
||
秒
|
||
</label>
|
||
<label className="flex items-center gap-1.5 text-xs">
|
||
<input type="checkbox" checked={network} onChange={(e) => setNetwork(e.target.checked)} />
|
||
允许联网
|
||
</label>
|
||
<div className="flex-1" />
|
||
<Kbd combo="Mod+Enter" className="text-faint" />
|
||
<button className="btn btn-primary tnum" onClick={() => void run()} disabled={busy} aria-keyshortcuts={ariaShortcut('Mod+Enter')}>
|
||
{busy ? <><Spinner /> 执行中 {formatDuration(clock - since.current)}</> : <><Play size={12} aria-hidden /> 执行</>}
|
||
</button>
|
||
</div>
|
||
|
||
<textarea className="field mono text-xs" rows={14} spellCheck={false} aria-label="代码"
|
||
value={code} onChange={(e) => setCode(e.target.value)}
|
||
onKeyDown={(e) => { if (matchShortcut(e.nativeEvent, 'Mod+Enter')) { e.preventDefault(); void run() } }} />
|
||
|
||
{result && (
|
||
<div className="mt-3" data-sandbox-result>
|
||
<div className="mb-1 flex flex-wrap items-center gap-2 text-xs">
|
||
<StatusBadge status={result.ok ? 'done' : 'failed'} size={12} decorative />
|
||
<span style={{ color: result.ok ? 'var(--text-dim)' : 'var(--err)' }}>{headline}</span>
|
||
{result.duration_ms != null && <span className="tnum text-faint">{formatDuration(result.duration_ms)}</span>}
|
||
{result.backend && <span className="chip mono">{result.backend}</span>}
|
||
</div>
|
||
{result.thrown && <ErrorState compact error={result.thrown} onRetry={() => void run()} />}
|
||
{result.stdout && (
|
||
<pre className="mono max-h-72 overflow-auto whitespace-pre-wrap rounded-lg border bg-panel p-2.5 text-xs">
|
||
{result.stdout}
|
||
</pre>
|
||
)}
|
||
{result.stderr && (
|
||
<pre className="mono mt-2 max-h-52 overflow-auto whitespace-pre-wrap rounded-lg border p-2.5 text-xs text-[var(--err)]"
|
||
style={{ borderColor: 'color-mix(in srgb, var(--err) 40%, var(--border))' }}>
|
||
{result.stderr}
|
||
</pre>
|
||
)}
|
||
{result.error && !result.thrown && <ErrorState compact error={result} className="mt-2" />}
|
||
</div>
|
||
)}
|
||
</div>
|
||
)
|
||
}
|
||
|
||
// -------------------------------------------------------------------------
|
||
|
||
/** 新建工具时参数的起手式:一个必填的字符串参数,URL 模板里正好能插它 */
|
||
const PARAMS_EXAMPLE = {
|
||
type: 'object',
|
||
properties: { query: { type: 'string', description: '查询关键词' } },
|
||
required: ['query'],
|
||
}
|
||
const PARAMS_NONE = { type: 'object', properties: {}, required: [] }
|
||
|
||
function CustomTools() {
|
||
const refresh = useCatalog((s) => s.refresh)
|
||
// 信任档在工具目录(GET /tools)里,按名字对上。停用的不在目录里,也就没有这一项
|
||
const catalogTools = useCatalog((s) => s.tools)
|
||
const trustOf = (row: any) => catalogTools.find((t) => t.source === 'custom' && t.id === row.name && hasTrust(t))
|
||
const navigate = useNavigate()
|
||
const [params, setParams] = useSearchParams()
|
||
const [rows, setRows] = useState<any[] | null>(null)
|
||
const [error, setError] = useState<unknown>(null)
|
||
const [editing, setEditing] = useState<any | null>(null)
|
||
const endpoints = useEndpoints()
|
||
|
||
// ?edit=<工具名>:运行失败说「参数定义写坏了」时直接打开那一个的编辑框,不用再翻列表。
|
||
// 读完就从地址里摘掉,免得关了弹窗、刷新一下又弹出来
|
||
const wanted = params.get('edit')
|
||
useEffect(() => {
|
||
if (!wanted || !rows) return
|
||
const row = rows.find((r) => r.name === wanted)
|
||
if (row) setEditing(row)
|
||
else toast.warn(`未找到名为「${wanted}」的自定义工具,可能已被删除或重命名`)
|
||
setParams((p) => { p.delete('edit'); return p }, { replace: true })
|
||
}, [wanted, rows])
|
||
|
||
const load = async () => {
|
||
try {
|
||
// 撤销窗口里的那条 DELETE 还没发:存完别的工具一重拉,它不能跟着回来
|
||
setRows(withoutDeferred(await api.customTools.list(), '/api/custom-tools'))
|
||
setError(null)
|
||
} catch (e) {
|
||
if (rows) toast.error(e)
|
||
else setError(e)
|
||
}
|
||
}
|
||
useEffect(() => { void load() }, [])
|
||
useOnReconnect(load)
|
||
|
||
const remove = (row: any) => deferDelete({
|
||
what: `工具「${row.name}」`,
|
||
url: `/api/custom-tools/${row.id}`,
|
||
hide: () => setRows((rs) => rs && rs.filter((r) => r.id !== row.id)),
|
||
restore: () => void load(),
|
||
commit: () => api.customTools.remove(row.id),
|
||
done: () => void refresh(),
|
||
})
|
||
|
||
const create = () => setEditing({ kind: 'http', config: {}, enabled: true })
|
||
|
||
return (
|
||
<div className="mx-auto max-w-4xl p-4">
|
||
<SectionBar title="自定义工具" hint="HTTP 模板,或在沙箱中执行的 Python 代码。启用后出现在工具库,节点中按名称引用。">
|
||
<button className="btn btn-primary btn-sm" onClick={create}><Plus size={12} aria-hidden /> 新建工具</button>
|
||
</SectionBar>
|
||
|
||
{rows === null ? (
|
||
error ? <ErrorState error={error} onRetry={() => void load()} /> : <Skeleton rows={3} height={52} gap={8} />
|
||
) : !rows.length ? (
|
||
<EmptyState
|
||
icon={<Wrench size={22} />}
|
||
title="还没有自定义工具"
|
||
body="把业务系统的查询接口封装成工具,模型即可按需调用。写好参数说明,无需保存即可试运行。"
|
||
action={<button className="btn btn-primary btn-sm" onClick={create}><Plus size={12} aria-hidden /> 新建工具</button>}
|
||
/>
|
||
) : (
|
||
<div className="space-y-2">
|
||
{rows.some(trustOf) && (
|
||
<p className="text-2xs leading-relaxed text-faint" data-trust-explain>
|
||
{TOOL_TRUST_TEXT.title}:{TOOL_TRUST_TEXT.explain}
|
||
</p>
|
||
)}
|
||
{rows.map((row) => (
|
||
<div key={row.id} className="flex items-center gap-2 rounded-lg border bg-panel px-3 py-2.5">
|
||
<div className="min-w-0 flex-1">
|
||
<div className="flex items-center gap-2">
|
||
<span className="mono text-sm font-medium">{row.name}</span>
|
||
<span className="chip">{row.kind === 'python' ? 'Python' : 'HTTP'}</span>
|
||
{row.kind === 'http' && row.config?.endpoint && (
|
||
<span className="chip" title={TOOL_ENDPOINT_TEXT.hint} data-custom-tool-bound="">
|
||
{TOOL_ENDPOINT_TEXT.bind} {endpoints?.find((e) => e.id === row.config.endpoint || e.name === row.config.endpoint)?.name
|
||
?? String(row.config.endpoint)}
|
||
</span>
|
||
)}
|
||
{row.problem && <ProblemChip problem={row.problem} />}
|
||
{!row.enabled && <span className="chip" title="停用的工具不出现在工具库和节点里">已停用</span>}
|
||
</div>
|
||
{row.problem
|
||
? <div className="truncate text-xs" style={{ color: 'var(--st-failed)' }} title={row.problem}>{row.problem}</div>
|
||
: <div className="truncate text-xs text-faint">{row.description || '未填写描述:模型无法判断何时调用该工具'}</div>}
|
||
</div>
|
||
<TrustControl tool={trustOf(row)} />
|
||
<button className="btn btn-sm" disabled={!row.enabled}
|
||
title={row.enabled ? '到工具库中带参数试运行' : '已停用的工具不在工具库中'}
|
||
onClick={() => navigate(`/tools/library/${row.name}`)}>
|
||
<Play size={11} aria-hidden /> 试运行
|
||
</button>
|
||
<button className="btn btn-sm btn-ghost" onClick={() => setEditing(row)}>编辑</button>
|
||
<DeleteButton label={`删除自定义工具 ${row.name}`} onClick={() => remove(row)} />
|
||
</div>
|
||
))}
|
||
</div>
|
||
)}
|
||
|
||
{editing && (
|
||
<CustomToolEditor
|
||
row={editing}
|
||
onClose={() => setEditing(null)}
|
||
onSaved={async (saved) => {
|
||
setEditing(null)
|
||
await load()
|
||
await refresh()
|
||
toast.ok(`已保存工具「${saved.name}」`)
|
||
}}
|
||
/>
|
||
)}
|
||
</div>
|
||
)
|
||
}
|
||
|
||
const TOOL_NAME_RE = /^[a-zA-Z_][a-zA-Z0-9_]*$/
|
||
|
||
function CustomToolEditor({ row, onClose, onSaved }: { row: any; onClose: () => void; onSaved: (saved: any) => void }) {
|
||
const [initial] = useState(() => ({
|
||
name: row.name ?? '', description: row.description ?? '', kind: row.kind ?? 'http',
|
||
// 只有新建时给起手式。已有的工具显示存着的样子,哪怕是 {}:后端按它生成参数
|
||
// 校验,悄悄换成示例的话只改一句描述也会把 query 存成必填,不带参数调用它的
|
||
// 节点从此过不了校验
|
||
parameters: row.id ? (row.parameters ?? PARAMS_NONE) : PARAMS_EXAMPLE,
|
||
config: row.config ?? {}, enabled: row.enabled ?? true,
|
||
}))
|
||
const [form, setForm] = useState<any>(initial)
|
||
// JsonInput 敲过字之后不再跟外面的值同步:插入示例时换个 key 让它重新挂载
|
||
const [paramsKey, setParamsKey] = useState(0)
|
||
const noParams = !Object.keys(form.parameters?.properties ?? {}).length
|
||
const [busy, setBusy] = useState(false)
|
||
const [args, setArgs] = useState<any>(() => exampleArgs(initial.parameters, true))
|
||
const [trial, setTrial] = useState<{ since?: number; result?: any; sig?: string } | null>(null)
|
||
const clock = useRunClock(!!trial?.since)
|
||
// 参数定义写坏了(保存被 422 拒掉,或者试跑时后端说格式不对):写在「参数 JSON Schema」
|
||
// 下面。以前是 toast,盖在弹窗标题上,几秒就没了
|
||
const [paramsError, setParamsError] = useState<string | null>(row.problem ?? null)
|
||
const paramsRef = useRef<HTMLDivElement>(null)
|
||
// 焦点也挪到参数框上:保存、试跑的按钮忙时禁用,焦点会掉到 body(弹窗外)。框标着
|
||
// aria-invalid 并指向那句原因,读屏聚焦就念出来——以前的 toast 在 assertive 区里是会念的
|
||
const showParamsError = (message: string) => {
|
||
setParamsError(message)
|
||
requestAnimationFrame(() => {
|
||
paramsRef.current?.scrollIntoView({ block: 'nearest' })
|
||
paramsRef.current?.querySelector('textarea')?.focus({ preventScroll: true })
|
||
})
|
||
}
|
||
|
||
const nameError = form.name && !TOOL_NAME_RE.test(form.name) ? '只能包含英文字母、数字和下划线,且不能以数字开头' : null
|
||
const dirty = JSON.stringify(form) !== JSON.stringify(initial)
|
||
// 绑定登记的端点(§3.9):config 是 {endpoint, method, path, query, body},只填路径,地址和认证头由端点按环境提供
|
||
const endpoints = useEndpoints()
|
||
const bound = form.kind === 'http' && !!form.config.endpoint
|
||
const missingConfig = [
|
||
form.kind === 'http' && !bound && !form.config.url && 'URL',
|
||
bound && !String(form.config.path ?? '').trim() && TOOL_ENDPOINT_TEXT.path,
|
||
form.kind === 'python' && !form.config.code && '代码',
|
||
].filter(Boolean) as string[]
|
||
const missing = [...(form.name ? [] : ['名称']), ...missingConfig]
|
||
// 试跑结果对应的是哪一份配置和参数:之后改了就把结果标成旧的,免得拿旧结果当新配置的
|
||
const trialSig = JSON.stringify([form.kind, form.parameters ?? {}, form.config, args ?? {}])
|
||
|
||
const submit = async () => {
|
||
if (missing.length || nameError) return
|
||
setBusy(true)
|
||
try {
|
||
const saved = row.id ? await api.customTools.update(row.id, form) : await api.customTools.create(form)
|
||
onSaved(saved ?? form)
|
||
} catch (e) {
|
||
if (e instanceof ApiError && e.status === 422 && /参数定义/.test(e.message)) showParamsError(e.message)
|
||
else toast.error(e)
|
||
} finally {
|
||
setBusy(false)
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 试跑眼前这份配置(testDraft),不落库。以前只能跑已保存的:新建要先保存,
|
||
* 改了代码也得先存——保存等于让节点立刻用上一个还没试过的版本
|
||
*/
|
||
const tryIt = async () => {
|
||
if (trial?.since || missingConfig.length) return
|
||
const sig = trialSig
|
||
setTrial({ since: Date.now() })
|
||
try {
|
||
const result = await api.customTools.testDraft({
|
||
name: form.name && !nameError ? form.name : undefined,
|
||
kind: form.kind, parameters: form.parameters ?? {}, config: form.config, args: args ?? {},
|
||
})
|
||
setTrial({ result, sig })
|
||
if (result?.ok === false && /^参数定义/.test(String(result.error ?? ''))) showParamsError(String(result.error))
|
||
} catch (e) {
|
||
setTrial({ result: { ok: false, thrown: e }, sig })
|
||
}
|
||
}
|
||
|
||
const setConfig = (patch: any) => setForm((f: any) => ({ ...f, config: { ...f.config, ...patch } }))
|
||
/**
|
||
* 换绑端点:绑定时 config 换成 {endpoint, method, path, query, body}(地址、请求头不再用:端点提供),不绑定时换回
|
||
* {method, url, headers, body, parse_json}。方法和请求体两边都留着
|
||
*/
|
||
const bindEndpoint = (ref: string) => setForm((f: any) => {
|
||
const { method, body } = f.config
|
||
return {
|
||
...f,
|
||
config: ref
|
||
? { endpoint: ref, method: method ?? 'GET', path: f.config.path ?? '', query: f.config.query ?? {}, ...(body !== undefined ? { body } : {}) }
|
||
: { method: method ?? 'GET', url: '', headers: {}, parse_json: true, ...(body !== undefined ? { body } : {}) },
|
||
}
|
||
})
|
||
const endpointValue = endpoints?.find((e) => e.id === form.config.endpoint || e.name === form.config.endpoint)?.id
|
||
?? form.config.endpoint ?? ''
|
||
const endpointMissing = bound && !!endpoints && !endpoints.some((e) => e.id === form.config.endpoint || e.name === form.config.endpoint)
|
||
|
||
return (
|
||
<Modal open onClose={onClose} dirty={dirty} title={row.id ? `编辑工具「${row.name}」` : '新建工具'} width={640}
|
||
footer={<>
|
||
<button className="btn" onClick={onClose}>取消</button>
|
||
<button className="btn btn-primary" onClick={() => void submit()}
|
||
disabled={busy || missing.length > 0 || !!nameError}
|
||
title={missing.length ? `还缺:${missing.join('、')}` : undefined}>
|
||
{busy ? <Spinner size={11} /> : null} 保存
|
||
</button>
|
||
</>}>
|
||
<div className="space-y-3">
|
||
<div className="grid grid-cols-[1fr_180px] gap-3">
|
||
<Field label="名称" required error={nameError} hint="英文名称,模型按此名称调用">
|
||
{(p) => (
|
||
<input {...p} className="field mono" value={form.name} placeholder="query_order_status" spellCheck={false}
|
||
onChange={(e) => setForm({ ...form, name: e.target.value })} />
|
||
)}
|
||
</Field>
|
||
<Field label="类型">
|
||
{(p) => (
|
||
<select {...p} className="field" value={form.kind} onChange={(e) => setForm({ ...form, kind: e.target.value })}>
|
||
<option value="http">HTTP 请求</option>
|
||
<option value="python">Python(沙箱执行)</option>
|
||
</select>
|
||
)}
|
||
</Field>
|
||
</div>
|
||
<Field label="描述" hint="模型据此判断何时调用,请写清楚">
|
||
{(p) => (
|
||
<textarea {...p} className="field" rows={2} value={form.description}
|
||
placeholder="按订单号查询订单状态,返回当前环节和更新时间"
|
||
onChange={(e) => setForm({ ...form, description: e.target.value })} />
|
||
)}
|
||
</Field>
|
||
<div ref={paramsRef} data-params-field>
|
||
<Field label="参数 JSON Schema" hint="为每个参数写清 description,模型据此填值" error={paramsError}>
|
||
{(p) => (
|
||
<>
|
||
<JsonInput key={paramsKey} {...p} value={form.parameters} rows={7}
|
||
onChange={(v) => { setParamsError(null); setForm((f: any) => ({ ...f, parameters: v })) }} />
|
||
{noParams && (
|
||
<div className="mt-1 flex items-center gap-2 text-2xs text-faint">
|
||
<span>当前无参数:模型调用时不传入任何参数</span>
|
||
<button type="button" className="btn btn-xs"
|
||
onClick={() => { setParamsError(null); setForm((f: any) => ({ ...f, parameters: PARAMS_EXAMPLE })); setParamsKey((k) => k + 1) }}>
|
||
<Wand2 size={11} aria-hidden /> 插入示例参数
|
||
</button>
|
||
</div>
|
||
)}
|
||
</>
|
||
)}
|
||
</Field>
|
||
</div>
|
||
|
||
{form.kind === 'http' && (
|
||
<Field label={TOOL_ENDPOINT_TEXT.bind} hint={endpoints && !endpoints.length ? TOOL_ENDPOINT_TEXT.noEndpoints : TOOL_ENDPOINT_TEXT.hint}
|
||
error={endpointMissing ? TOOL_ENDPOINT_TEXT.missing(String(form.config.endpoint)) : undefined}>
|
||
{(p) => (
|
||
<select {...p} className="field" value={endpointValue} onChange={(e) => bindEndpoint(e.target.value)}
|
||
data-custom-tool-endpoint="">
|
||
<option value="">{TOOL_ENDPOINT_TEXT.none}</option>
|
||
{(endpoints ?? []).map((ep) => <option key={ep.id} value={ep.id}>{ep.name}</option>)}
|
||
{endpointMissing && <option value={endpointValue} disabled>{String(form.config.endpoint)}</option>}
|
||
</select>
|
||
)}
|
||
</Field>
|
||
)}
|
||
{form.kind === 'http' && bound ? (
|
||
<>
|
||
<div className="grid grid-cols-[110px_1fr] gap-3">
|
||
<Field label="方法">
|
||
{(p) => (
|
||
<select {...p} className="field" value={form.config.method ?? 'GET'}
|
||
onChange={(e) => setConfig({ method: e.target.value })}>
|
||
{['GET', 'POST', 'PUT', 'PATCH', 'DELETE'].map((m) => <option key={m}>{m}</option>)}
|
||
</select>
|
||
)}
|
||
</Field>
|
||
<Field label={TOOL_ENDPOINT_TEXT.path} required hint={TOOL_ENDPOINT_TEXT.pathHint}>
|
||
{(p) => (
|
||
<input {...p} className="field mono text-xs" value={form.config.path ?? ''} placeholder="/orders/{{ order_id }}"
|
||
onChange={(e) => setConfig({ path: e.target.value })} data-custom-tool-path="" />
|
||
)}
|
||
</Field>
|
||
</div>
|
||
<Field label={TOOL_ENDPOINT_TEXT.query}>
|
||
{(p) => <JsonInput id={p.id} value={form.config.query ?? {}} rows={3} onChange={(v) => setConfig({ query: v ?? {} })} />}
|
||
</Field>
|
||
<Field label={TOOL_ENDPOINT_TEXT.body}>
|
||
{(p) => <JsonInput id={p.id} value={form.config.body} rows={4} onChange={(v) => setConfig({ body: v })} />}
|
||
</Field>
|
||
</>
|
||
) : form.kind === 'http' ? (
|
||
<>
|
||
<div className="grid grid-cols-[110px_1fr] gap-3">
|
||
<Field label="方法">
|
||
{(p) => (
|
||
<select {...p} className="field" value={form.config.method ?? 'GET'}
|
||
onChange={(e) => setConfig({ method: e.target.value })}>
|
||
{['GET', 'POST', 'PUT', 'PATCH', 'DELETE'].map((m) => <option key={m}>{m}</option>)}
|
||
</select>
|
||
)}
|
||
</Field>
|
||
<Field label={<>URL <span className="font-normal text-faint">(可用 {'{{ 参数名 }}'} 插值)</span></>} required>
|
||
{(p) => (
|
||
<input {...p} className="field mono text-xs" value={form.config.url ?? ''}
|
||
placeholder="https://api.example.com/search?q={{ query }}"
|
||
onChange={(e) => setConfig({ url: e.target.value })} />
|
||
)}
|
||
</Field>
|
||
</div>
|
||
<label className="flex items-center gap-1.5 text-xs">
|
||
<input type="checkbox" checked={!!form.config.parse_json}
|
||
onChange={(e) => setConfig({ parse_json: e.target.checked })} />
|
||
按 JSON 解析响应
|
||
</label>
|
||
<Field label="请求头">
|
||
{(p) => <JsonInput id={p.id} value={form.config.headers ?? {}} rows={3} onChange={(v) => setConfig({ headers: v })} />}
|
||
</Field>
|
||
<Field label="请求体(JSON,可插值)">
|
||
{(p) => <JsonInput id={p.id} value={form.config.body} rows={4} onChange={(v) => setConfig({ body: v })} />}
|
||
</Field>
|
||
</>
|
||
) : (
|
||
<Field label="Python 代码" required hint="参数位于 args 变量中,用 print 输出结果">
|
||
{(p) => (
|
||
<textarea {...p} className="field mono text-xs" rows={10} spellCheck={false}
|
||
value={form.config.code ?? ''}
|
||
placeholder={'import json\nprint(json.dumps({"echo": args}))'}
|
||
onChange={(e) => setConfig({ code: e.target.value })} />
|
||
)}
|
||
</Field>
|
||
)}
|
||
|
||
<label className="flex items-center gap-2 text-xs">
|
||
<input type="checkbox" checked={!!form.enabled} onChange={(e) => setForm({ ...form, enabled: e.target.checked })} />
|
||
启用<span className="text-2xs text-faint">停用后不出现在工具库和节点里</span>
|
||
</label>
|
||
|
||
<div className="rounded-lg border bg-bg p-2.5" data-tool-trial>
|
||
<div className="mb-1.5 flex items-center gap-2">
|
||
<span className="text-xs font-medium">试运行</span>
|
||
<span className="text-2xs text-faint">
|
||
{!row.id
|
||
? '使用当前配置试运行,无需先保存'
|
||
: dirty ? '使用当前配置(含未保存的改动),已保存的版本不受影响' : '传入参数试运行,查看返回结果'}
|
||
</span>
|
||
<button className="btn btn-xs ml-auto" onClick={() => setArgs(exampleArgs(form.parameters, true))}
|
||
title="按参数 Schema 重新填充示例">
|
||
<Wand2 size={11} aria-hidden /> 按 Schema 填充示例
|
||
</button>
|
||
</div>
|
||
<JsonInput value={args} onChange={setArgs} rows={3} placeholder="{}" />
|
||
<button className="btn btn-sm tnum mt-2" disabled={!!trial?.since || missingConfig.length > 0}
|
||
title={missingConfig.length ? `还缺:${missingConfig.join('、')}` : '使用当前配置和参数试运行,不保存'}
|
||
onClick={() => void tryIt()}>
|
||
{trial?.since
|
||
? <><Spinner size={11} /> 试运行中 {formatDuration(clock - trial.since)}</>
|
||
: <><Play size={11} aria-hidden /> 试运行</>}
|
||
</button>
|
||
{trial?.result && <ToolResult result={trial.result} stale={trial.sig !== trialSig} />}
|
||
</div>
|
||
</div>
|
||
</Modal>
|
||
)
|
||
}
|
||
|
||
// -------------------------------------------------------------------------
|
||
|
||
/**
|
||
* 后端记着的上次探测(last_check_*,含启动和「重新加载」时的那次连接)。成功时
|
||
* 补一句发现了几个工具——探测的结论后端只记了连没连上,工具数在 tools_cache 里
|
||
*/
|
||
function mcpServerRecord(row: any): HealthRecord | undefined {
|
||
const rec = healthFromServer(row)
|
||
return rec?.ok ? { ...rec, note: `发现 ${row.tools_cache?.length ?? 0} 个工具` } : rec
|
||
}
|
||
|
||
/** 决定连哪个进程 / 地址的那几项。改了它们,上次探测的结果说的就是另一个服务了 */
|
||
const mcpConnection = (f: any) => JSON.stringify([f.transport, f.command.trim(), f.args.trim(), f.env ?? {}, f.url.trim(),
|
||
f.headers ?? {}, f.endpoint_id ?? null])
|
||
|
||
/** 登记的端点(绑定用)。取不到时为空列表,照样能不绑定 */
|
||
function useEndpoints(): EndpointRow[] | null {
|
||
const [rows, setRows] = useState<EndpointRow[] | null>(null)
|
||
useEffect(() => { api.endpoints.list().then(({ items }) => setRows(items), () => setRows([])) }, [])
|
||
return rows
|
||
}
|
||
|
||
/**
|
||
* 认证头按行编辑:名称、值。已存的值服务端只回掩码,不改的保持掩码原样提交(表示保持原值);新值加密保存
|
||
*/
|
||
function HeadersEditor({ value, onChange, disabled }: {
|
||
value: Record<string, string>; onChange: (v: Record<string, string>) => void; disabled?: boolean
|
||
}) {
|
||
const [rows, setRows] = useState(() => Object.entries(value ?? {}).map(([k, v]) => ({ k, v })))
|
||
const push = (next: { k: string; v: string }[]) => {
|
||
setRows(next)
|
||
onChange(Object.fromEntries(next.filter((r) => r.k.trim()).map((r) => [r.k.trim(), r.v])))
|
||
}
|
||
return (
|
||
<div className="space-y-1.5" data-mcp-headers={rows.length}>
|
||
{rows.map((r, i) => (
|
||
<div key={i} className="flex items-center gap-2">
|
||
<input className="field mono w-44 text-xs" value={r.k} placeholder="Authorization" disabled={disabled}
|
||
aria-label={`${MCP_AUTH_TEXT.headerName} ${i + 1}`}
|
||
onChange={(e) => push(rows.map((x, j) => (j === i ? { ...x, k: e.target.value } : x)))} />
|
||
<input className="field mono min-w-0 flex-1 text-xs" value={r.v} disabled={disabled} autoComplete="off"
|
||
aria-label={`${MCP_AUTH_TEXT.headerValue} ${i + 1}`} data-mcp-header-value=""
|
||
onChange={(e) => push(rows.map((x, j) => (j === i ? { ...x, v: e.target.value } : x)))} />
|
||
<DeleteButton label={`${MCP_AUTH_TEXT.headerName} ${r.k || i + 1}`} disabled={disabled}
|
||
onClick={() => push(rows.filter((_, j) => j !== i))} />
|
||
</div>
|
||
))}
|
||
<button type="button" className="btn btn-xs" disabled={disabled} onClick={() => push([...rows, { k: '', v: '' }])}
|
||
data-mcp-header-add="">
|
||
<Plus size={10} aria-hidden /> {MCP_AUTH_TEXT.addHeader}
|
||
</button>
|
||
</div>
|
||
)
|
||
}
|
||
|
||
function McpServers() {
|
||
const refresh = useCatalog((s) => s.refresh)
|
||
const tools = useCatalog((s) => s.tools)
|
||
const workflows = useCatalog((s) => s.workflows)
|
||
const [rows, setRows] = useState<any[] | null>(null)
|
||
const [error, setError] = useState<unknown>(null)
|
||
const [editing, setEditing] = useState<any | null>(null)
|
||
const [reloading, setReloading] = useState(false)
|
||
|
||
const load = async () => {
|
||
try {
|
||
setRows(await api.mcp.list())
|
||
setError(null)
|
||
} catch (e) {
|
||
if (rows) toast.error(e)
|
||
else setError(e)
|
||
}
|
||
}
|
||
useEffect(() => { void load() }, [])
|
||
useOnReconnect(load)
|
||
|
||
const reloadAll = async () => {
|
||
setReloading(true)
|
||
try {
|
||
await api.mcp.refresh()
|
||
await load()
|
||
await refresh()
|
||
toast.ok('已重新加载 MCP 服务')
|
||
} catch (e) {
|
||
toast.error(e)
|
||
} finally {
|
||
setReloading(false)
|
||
}
|
||
}
|
||
|
||
const remove = async (row: any) => {
|
||
const ids = [
|
||
...tools.filter((t) => t.source === 'mcp' && t.id.startsWith(`mcp:${row.name}/`)).map((t) => t.id),
|
||
...(row.tools_cache ?? []).map((t: string) => `mcp:${row.name}/${t}`),
|
||
]
|
||
const using = workflowsMentioning(workflows, [...new Set(ids)])
|
||
const ok = await confirmDialog({
|
||
title: `删除 MCP 服务「${row.name}」?`,
|
||
danger: true,
|
||
consequences: [
|
||
row.tools_cache?.length ? `该服务的 ${row.tools_cache.length} 个工具将从工具库移除` : '',
|
||
using.length ? `${workflowList(using)}使用了该服务的工具,运行到相应步骤时会失败` : '目前没有工作流使用该服务的工具',
|
||
].filter(Boolean),
|
||
confirmLabel: '删除服务',
|
||
})
|
||
if (!ok) return
|
||
try {
|
||
await api.mcp.remove(row.id)
|
||
forgetHealth(`mcp:${row.id}`)
|
||
setRows((rs) => rs && rs.filter((r) => r.id !== row.id))
|
||
await refresh()
|
||
toast.ok(`已删除 MCP 服务「${row.name}」`)
|
||
} catch (e) {
|
||
toast.error(e)
|
||
}
|
||
}
|
||
|
||
// 本地子进程会在服务器上执行命令,只有管理员能建(A6 第 6 条):别的角色新建时默认 HTTP
|
||
const admin = useAtLeast('admin')
|
||
const create = () => setEditing(admin ? { transport: 'stdio', args: [], env: {}, enabled: true }
|
||
: { transport: 'http', args: [], env: {}, headers: {}, enabled: true })
|
||
|
||
return (
|
||
<div className="mx-auto max-w-4xl p-4">
|
||
<SectionBar
|
||
title="MCP 接入"
|
||
hint={<>接入后工具出现在工具库,节点里用 <code className="mono">mcp:服务名/工具名</code> 引用。</>}
|
||
>
|
||
<button className="btn btn-sm" onClick={() => void reloadAll()} disabled={reloading}
|
||
title="重新连接所有已启用的服务,并刷新工具清单">
|
||
{reloading ? <Spinner size={11} /> : <RefreshCw size={12} aria-hidden />} 重新加载
|
||
</button>
|
||
<button className="btn btn-primary btn-sm" onClick={create}><Plus size={12} aria-hidden /> 添加服务</button>
|
||
</SectionBar>
|
||
|
||
{rows === null ? (
|
||
error ? <ErrorState error={error} onRetry={() => void load()} /> : <Skeleton rows={2} height={60} gap={8} />
|
||
) : !rows.length ? (
|
||
<EmptyState
|
||
icon={<Plug size={22} />}
|
||
title="还没有接入 MCP 服务"
|
||
body="接入文件系统、数据库、浏览器自动化等现成的 MCP 服务,即可获得一组新工具。"
|
||
action={<button className="btn btn-primary btn-sm" onClick={create}><Plus size={12} aria-hidden /> 添加服务</button>}
|
||
/>
|
||
) : (
|
||
<div className="space-y-2.5">
|
||
{tools.some((t) => t.source === 'mcp' && hasTrust(t)) && (
|
||
<p className="text-2xs leading-relaxed text-faint" data-trust-explain>
|
||
{TOOL_TRUST_TEXT.title}:{TOOL_TRUST_TEXT.explain}
|
||
</p>
|
||
)}
|
||
{rows.map((row) => (
|
||
<McpCard key={row.id} row={row} onEdit={() => setEditing(row)} onRemove={() => void remove(row)}
|
||
onProbed={async () => { await load(); await refresh() }} />
|
||
))}
|
||
</div>
|
||
)}
|
||
|
||
{editing && (
|
||
<McpEditor row={editing} onClose={() => setEditing(null)}
|
||
onSaved={async (name, reconnected) => {
|
||
// 本机记的那次探测说的是改之前的命令 / 地址(后端同样清掉了自己记的)
|
||
if (reconnected && editing.id) forgetHealth(`mcp:${editing.id}`)
|
||
setEditing(null)
|
||
await load()
|
||
await refresh()
|
||
toast.ok(`已保存 MCP 服务「${name}」`)
|
||
}} />
|
||
)}
|
||
</div>
|
||
)
|
||
}
|
||
|
||
function McpCard({ row, onEdit, onRemove, onProbed }: {
|
||
row: any; onEdit: () => void; onRemove: () => void; onProbed: () => Promise<void>
|
||
}) {
|
||
const key = `mcp:${row.id}`
|
||
const { record: shown, checkingSince } = useHealth(key, mcpServerRecord(row))
|
||
// 这台服务的工具,逐个设信任档(键是 mcp:服务名/工具名)
|
||
const trusted = useCatalog((s) => s.tools).filter((t) => t.source === 'mcp' && t.id.startsWith(`mcp:${row.name}/`) && hasTrust(t))
|
||
const probe = async () => {
|
||
await checkHealth(key, async () => {
|
||
const t0 = performance.now()
|
||
const res = await api.mcp.probe(row.id)
|
||
return {
|
||
// 后端量的是连上并列出工具的时间;老后端没有就用往返时间
|
||
ok: !!res.ok, ms: res.elapsed_ms ?? Math.round(performance.now() - t0),
|
||
error: res.error, hint: res.hint, detail: res.detail,
|
||
note: res.ok ? `发现 ${res.tools?.length ?? 0} 个工具` : undefined,
|
||
}
|
||
})
|
||
await onProbed()
|
||
}
|
||
return (
|
||
<article className="rounded-lg border bg-panel px-3 py-2.5">
|
||
<div className="flex flex-wrap items-center gap-x-2 gap-y-1.5">
|
||
<Plug size={14} className="text-dim" aria-hidden />
|
||
<span className="text-sm font-medium">{row.name}</span>
|
||
<span className="chip">{row.transport === 'stdio' ? '本地子进程' : 'HTTP'}</span>
|
||
{!!row.tools_cache?.length && <span className="chip tnum">{row.tools_cache.length} 个工具</span>}
|
||
{row.enabled === false && <span className="chip">已停用</span>}
|
||
<span className="flex-1" />
|
||
<HealthPill record={shown} checkingSince={checkingSince} />
|
||
<div className="flex items-center gap-1">
|
||
<button className="btn btn-sm" disabled={!!checkingSince} onClick={() => void probe()}>
|
||
<Plug size={11} aria-hidden /> 测试连接
|
||
</button>
|
||
<button className="btn btn-sm btn-ghost" onClick={onEdit}>编辑</button>
|
||
<DeleteButton label={`删除 MCP 服务 ${row.name}`} onClick={onRemove} />
|
||
</div>
|
||
</div>
|
||
<div className="mono mt-1.5 break-all text-2xs text-faint">
|
||
{row.transport === 'stdio' ? `${row.command ?? ''} ${(row.args ?? []).join(' ')}` : row.url}
|
||
</div>
|
||
{trusted.length > 0 && (
|
||
<ul className="mt-2 rounded-md border bg-bg" aria-label={`${row.name} 的工具`}>
|
||
{trusted.map((t) => (
|
||
<li key={t.id} className="flex items-center gap-2 border-b border-[var(--hairline)] px-2.5 py-1.5 last:border-0">
|
||
<span className="mono shrink-0 text-xs">{t.name}</span>
|
||
<span className="min-w-0 flex-1 truncate text-2xs text-faint" title={t.description}>{t.description}</span>
|
||
<TrustControl tool={t} />
|
||
</li>
|
||
))}
|
||
</ul>
|
||
)}
|
||
{shown && !shown.ok && !checkingSince && (
|
||
<ErrorState compact error={shown} onRetry={() => void probe()} className="mt-2" />
|
||
)}
|
||
</article>
|
||
)
|
||
}
|
||
|
||
function McpEditor({ row, onClose, onSaved }: {
|
||
row: any; onClose: () => void
|
||
/** reconnected:连接配置改过了,之前的探测结果不再代表它 */
|
||
onSaved: (name: string, reconnected: boolean) => void
|
||
}) {
|
||
const admin = useAtLeast('admin')
|
||
const endpoints = useEndpoints()
|
||
const [initial] = useState(() => ({
|
||
name: row.name ?? '', transport: row.transport ?? 'stdio', command: row.command ?? '',
|
||
args: (row.args ?? []).join(' '), env: row.env ?? {}, url: row.url ?? '', enabled: row.enabled ?? true,
|
||
headers: row.headers ?? {}, endpoint_id: row.endpoint_id ?? null,
|
||
}))
|
||
const [form, setForm] = useState<any>(initial)
|
||
const [busy, setBusy] = useState(false)
|
||
const dirty = JSON.stringify(form) !== JSON.stringify(initial)
|
||
// 本地子进程只有管理员能建、能改:已有的本地子进程服务对别的角色只读
|
||
const locked = !admin && initial.transport === 'stdio' && !!row.id
|
||
const missing = [
|
||
!form.name.trim() && '名称',
|
||
form.transport === 'stdio' && !form.command.trim() && '命令',
|
||
form.transport !== 'stdio' && !form.endpoint_id && !form.url.trim() && 'URL',
|
||
].filter(Boolean) as string[]
|
||
|
||
const submit = async () => {
|
||
if (missing.length) return
|
||
setBusy(true)
|
||
try {
|
||
const payload = { ...form, args: form.args.split(/\s+/).filter(Boolean) }
|
||
if (row.id) await api.mcp.update(row.id, payload)
|
||
else await api.mcp.create(payload)
|
||
onSaved(form.name, mcpConnection(form) !== mcpConnection(initial))
|
||
} catch (e) {
|
||
toast.error(e)
|
||
} finally {
|
||
setBusy(false)
|
||
}
|
||
}
|
||
|
||
return (
|
||
<Modal open onClose={onClose} dirty={dirty} title={row.id ? `编辑 MCP 服务「${row.name}」` : '添加 MCP 服务'}
|
||
footer={<>
|
||
<button className="btn" onClick={onClose}>取消</button>
|
||
{!locked && (
|
||
<button className="btn btn-primary" onClick={() => void submit()} disabled={busy || missing.length > 0}
|
||
title={missing.length ? `还缺:${missing.join('、')}` : undefined}>
|
||
{busy ? <Spinner size={11} /> : null} 保存
|
||
</button>
|
||
)}
|
||
</>}>
|
||
<fieldset disabled={locked} className="m-0 min-w-0 space-y-3 border-0 p-0" data-mcp-editor={form.transport}>
|
||
{locked && <p className="text-2xs" style={{ color: 'var(--st-waiting)' }} data-mcp-stdio-locked="">{MCP_AUTH_TEXT.stdioReadOnly}</p>}
|
||
<div className="grid grid-cols-[1fr_200px] gap-3">
|
||
<Field label="名称" required hint="节点里按 mcp:名称/工具名 引用">
|
||
{(p) => (
|
||
<input {...p} className="field" value={form.name} placeholder="filesystem"
|
||
onChange={(e) => setForm({ ...form, name: e.target.value })} />
|
||
)}
|
||
</Field>
|
||
<Field label="传输方式">
|
||
{(p) => (
|
||
<select {...p} className="field" value={form.transport}
|
||
onChange={(e) => setForm({ ...form, transport: e.target.value })}>
|
||
<option value="stdio" disabled={!admin}>stdio(本地子进程)</option>
|
||
<option value="http">HTTP(远程)</option>
|
||
</select>
|
||
)}
|
||
</Field>
|
||
</div>
|
||
{!admin && !locked && <p className="text-2xs text-faint" data-mcp-stdio-admin="">{MCP_AUTH_TEXT.stdioAdmin}</p>}
|
||
{form.transport === 'stdio' ? (
|
||
<>
|
||
<Field label="命令" required>
|
||
{(p) => (
|
||
<input {...p} className="field mono text-xs" value={form.command} placeholder="npx"
|
||
onChange={(e) => setForm({ ...form, command: e.target.value })} />
|
||
)}
|
||
</Field>
|
||
<Field label="参数" hint="空格分隔">
|
||
{(p) => (
|
||
<input {...p} className="field mono text-xs" value={form.args}
|
||
placeholder="-y @modelcontextprotocol/server-filesystem /tmp"
|
||
onChange={(e) => setForm({ ...form, args: e.target.value })} />
|
||
)}
|
||
</Field>
|
||
<Field label="环境变量">
|
||
{(p) => <JsonInput id={p.id} value={form.env} onChange={(v) => setForm({ ...form, env: v ?? {} })} rows={3} />}
|
||
</Field>
|
||
</>
|
||
) : (
|
||
<>
|
||
<Field label={MCP_AUTH_TEXT.endpoint} hint={MCP_AUTH_TEXT.endpointHint}>
|
||
{(p) => (
|
||
<select {...p} className="field" value={form.endpoint_id ?? ''} data-mcp-endpoint=""
|
||
onChange={(e) => setForm({ ...form, endpoint_id: e.target.value || null })}>
|
||
<option value="">{MCP_AUTH_TEXT.endpointNone}</option>
|
||
{(endpoints ?? []).map((ep) => <option key={ep.id} value={ep.id}>{ep.name}</option>)}
|
||
{form.endpoint_id && endpoints && !endpoints.some((ep) => ep.id === form.endpoint_id) && (
|
||
<option value={form.endpoint_id} disabled>{TOOL_ENDPOINT_TEXT.missing(form.endpoint_id)}</option>
|
||
)}
|
||
</select>
|
||
)}
|
||
</Field>
|
||
<Field label={form.endpoint_id ? TOOL_ENDPOINT_TEXT.path : 'URL'} required={!form.endpoint_id}>
|
||
{(p) => (
|
||
<input {...p} className="field mono text-xs" value={form.url}
|
||
placeholder={form.endpoint_id ? '/mcp' : 'https://example.com/mcp'}
|
||
onChange={(e) => setForm({ ...form, url: e.target.value })} />
|
||
)}
|
||
</Field>
|
||
<Field label={MCP_AUTH_TEXT.headers} hint={MCP_AUTH_TEXT.headersHint}>
|
||
{() => <HeadersEditor value={form.headers} disabled={locked} onChange={(v) => setForm((f: any) => ({ ...f, headers: v }))} />}
|
||
</Field>
|
||
</>
|
||
)}
|
||
<label className="flex items-center gap-2 text-xs">
|
||
<input type="checkbox" checked={!!form.enabled} onChange={(e) => setForm({ ...form, enabled: e.target.checked })} />
|
||
启用
|
||
</label>
|
||
</fieldset>
|
||
</Modal>
|
||
)
|
||
}
|