Merge pull request #155 from RuoJi6/mcp-server-implementation

This commit is contained in:
ji ruo committed 2026-11-14 20:51:24 +08:00
commit cc1d84d573
14 files changed
+3397 -31

No files matched your search

@@ -108,6 +108,7 @@ export function BasicAuthCard() {
<FieldDescription>{t("settings.basicAuthPasswordHelp")}</FieldDescription>
</Field>
<FieldDescription>{t("settings.basicAuthSessionHelp")}</FieldDescription>
<FieldDescription>{t("settings.basicAuthMcpNote")}</FieldDescription>
{error ? (
<p role="alert" className="text-destructive text-sm">
{t(error.key, { message: localizedError(error.cause, t) })}
@@ -0,0 +1,596 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { CopyIcon, PlugZapIcon, PlusIcon, RefreshCwIcon } from "lucide-react";
import { toast } from "sonner";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Field, FieldDescription, FieldGroup, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { localizedError } from "@/i18n/errors";
import { useDateLocale } from "@/i18n/use-date-locale";
import { useLiveTranslation } from "@/i18n/use-live-translation";
import {
api,
type McpServerAuditEntry,
type McpServerScope,
type McpServerSettings,
type McpServerToken,
} from "@/lib/api";
import type { Company } from "@/lib/types";
// API scope value -> translation key suffix. Scope values contain ":", which
// i18next reads as a namespace separator, so they cannot be used as keys.
const SCOPES: { value: McpServerScope; key: string }[] = [
{ value: "read", key: "read" },
{ value: "task:create", key: "taskCreate" },
{ value: "task:control", key: "taskControl" },
];
type TokenStatus = "active" | "revoked" | "expired";
function tokenStatus(token: McpServerToken): TokenStatus {
if (token.revoked_at) return "revoked";
if (token.expires_at && new Date(token.expires_at).getTime() <= Date.now()) return "expired";
return "active";
}
function formatTime(iso: string, locale: string): string {
const d = new Date(iso);
return Number.isNaN(d.getTime()) ? iso : d.toLocaleString(locale, { hour12: false });
}
async function copyText(text: string) {
try {
await navigator.clipboard.writeText(text);
} catch {
// navigator.clipboard is unavailable on plain-HTTP LAN origins.
const ta = document.createElement("textarea");
ta.value = text;
ta.style.position = "fixed";
ta.style.opacity = "0";
document.body.appendChild(ta);
ta.select();
try {
document.execCommand("copy");
} finally {
document.body.removeChild(ta);
}
}
}
const emptyForm = {
name: "",
scopes: ["read"] as McpServerScope[],
companyIds: [] as number[],
days: "0",
maxActive: "0",
maxHourly: "0",
};
export function McpServerCard() {
const { t } = useLiveTranslation();
const { locale } = useDateLocale();
const [settings, setSettings] = useState<McpServerSettings | null>(null);
const [tokens, setTokens] = useState<McpServerToken[]>([]);
const [audit, setAudit] = useState<McpServerAuditEntry[]>([]);
const [companies, setCompanies] = useState<Company[]>([]);
const [allowedIps, setAllowedIps] = useState("");
const [trustedProxies, setTrustedProxies] = useState("");
const [savingAccess, setSavingAccess] = useState(false);
const [error, setError] = useState<unknown>(null);
const [saving, setSaving] = useState(false);
const [createOpen, setCreateOpen] = useState(false);
const [form, setForm] = useState(emptyForm);
const [creating, setCreating] = useState(false);
const [createError, setCreateError] = useState<unknown>(null);
const [createdToken, setCreatedToken] = useState<string | null>(null);
const [confirm, setConfirm] = useState<{ action: "revoke" | "delete"; token: McpServerToken } | null>(null);
const load = useCallback(async () => {
setError(null);
try {
const [nextSettings, nextTokens, nextAudit] = await Promise.all([
api.mcpServerSettings(),
api.mcpServerTokens(),
api.mcpServerAudit(),
]);
setSettings(nextSettings);
setAllowedIps(nextSettings.allowed_ips.join("\n"));
setTrustedProxies(nextSettings.trusted_proxies.join("\n"));
setTokens(nextTokens);
setAudit(nextAudit);
} catch (e) {
setError(e);
}
}, []);
useEffect(() => {
void load();
}, [load]);
const endpoint = typeof window === "undefined" || !settings ? "" : `${window.location.origin}${settings.path}`;
const copy = async (text: string) => {
await copyText(text);
toast.success(t("settings.mcpServer.copied"));
};
const toggle = async (enabled: boolean) => {
setSaving(true);
try {
setSettings(await api.setMcpServerEnabled(enabled));
toast.success(enabled ? t("settings.mcpServer.enabled") : t("settings.mcpServer.disabled"));
} catch (e) {
toast.error(t("settings.saveFailed", { message: localizedError(e, t) }));
} finally {
setSaving(false);
}
};
const saveAccess = async (event: React.FormEvent) => {
event.preventDefault();
setSavingAccess(true);
try {
const next = await api.setMcpServerAccess({
allowed_ips: allowedIps.split("\n"),
trusted_proxies: trustedProxies.split("\n"),
});
setSettings(next);
// Show the canonical form the server stored (trimmed, deduplicated, masked).
setAllowedIps(next.allowed_ips.join("\n"));
setTrustedProxies(next.trusted_proxies.join("\n"));
toast.success(t("settings.mcpServer.allowlistSaved"));
} catch (e) {
toast.error(t("settings.saveFailed", { message: localizedError(e, t) }));
} finally {
setSavingAccess(false);
}
};
const openCreate = () => {
setForm(emptyForm);
setCreateError(null);
setCreateOpen(true);
api
.companies()
.then(setCompanies)
.catch(() => setCompanies([]));
};
const toggleIn = <T,>(list: T[], value: T, on: boolean) => (on ? [...list, value] : list.filter((v) => v !== value));
const create = async (event: React.FormEvent) => {
event.preventDefault();
setCreating(true);
setCreateError(null);
try {
const result = await api.createMcpServerToken({
name: form.name.trim(),
scopes: form.scopes,
company_ids: form.companyIds,
expires_in_days: Number.parseInt(form.days, 10) || 0,
max_active_tasks: Number.parseInt(form.maxActive, 10) || 0,
max_tasks_per_hour: Number.parseInt(form.maxHourly, 10) || 0,
});
setCreateOpen(false);
setCreatedToken(result.token);
void load();
} catch (e) {
setCreateError(e);
} finally {
setCreating(false);
}
};
const runConfirmed = async () => {
if (!confirm) return;
const { action, token } = confirm;
setConfirm(null);
try {
if (action === "revoke") {
await api.revokeMcpServerToken(token.id);
toast.success(t("settings.mcpServer.revoked"));
} else {
await api.deleteMcpServerToken(token.id);
toast.success(t("settings.mcpServer.deleted"));
}
void load();
} catch (e) {
toast.error(t("settings.saveFailed", { message: localizedError(e, t) }));
}
};
const limit = (n: number) => (n > 0 ? String(n) : t("settings.mcpServer.unlimited"));
return (
<Card className="mb-4 break-inside-avoid md:mb-6">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<PlugZapIcon className="size-4" />
{t("settings.mcpServer.title")}
</CardTitle>
<CardDescription>{t("settings.mcpServer.help")}</CardDescription>
</CardHeader>
<CardContent>
<FieldGroup>
<Field orientation="horizontal">
<FieldLabel htmlFor="mcp-server-enabled">{t("settings.mcpServer.enable")}</FieldLabel>
<Switch
id="mcp-server-enabled"
checked={settings?.enabled ?? false}
onCheckedChange={toggle}
disabled={!settings || saving}
/>
</Field>
<Field>
<FieldLabel htmlFor="mcp-server-endpoint">{t("settings.mcpServer.endpoint")}</FieldLabel>
<div className="flex gap-2">
<Input id="mcp-server-endpoint" readOnly value={endpoint} className="font-mono text-xs" />
<Button type="button" variant="outline" disabled={!endpoint} onClick={() => copy(endpoint)}>
<CopyIcon />
{t("settings.mcpServer.copy")}
</Button>
</div>
<FieldDescription>{t("settings.mcpServer.endpointHelp")}</FieldDescription>
<FieldDescription className="text-foreground">{t("settings.mcpServer.noBasicAuth")}</FieldDescription>
{settings?.basic_auth_enabled ? (
<FieldDescription>{t("settings.mcpServer.basicAuthOn")}</FieldDescription>
) : null}
</Field>
<form onSubmit={saveAccess} className="flex flex-col gap-4">
<Field>
<FieldLabel htmlFor="mcp-server-allowlist">{t("settings.mcpServer.allowlist")}</FieldLabel>
<Textarea
id="mcp-server-allowlist"
rows={3}
className="font-mono text-xs"
value={allowedIps}
disabled={!settings || savingAccess}
placeholder={t("settings.mcpServer.allowlistPlaceholder")}
onChange={(e) => setAllowedIps(e.target.value)}
/>
<FieldDescription>{t("settings.mcpServer.allowlistHelp")}</FieldDescription>
{settings?.client_ip ? (
<FieldDescription>{t("settings.mcpServer.clientIp", { ip: settings.client_ip })}</FieldDescription>
) : null}
</Field>
<Field>
<FieldLabel htmlFor="mcp-server-proxies">{t("settings.mcpServer.trustedProxies")}</FieldLabel>
<Textarea
id="mcp-server-proxies"
rows={2}
className="font-mono text-xs"
value={trustedProxies}
disabled={!settings || savingAccess}
placeholder={t("settings.mcpServer.trustedProxiesPlaceholder")}
onChange={(e) => setTrustedProxies(e.target.value)}
/>
<FieldDescription>{t("settings.mcpServer.trustedProxiesHelp")}</FieldDescription>
</Field>
<div>
<Button type="submit" variant="outline" disabled={!settings || savingAccess}>
{savingAccess ? t("settings.saving") : t("settings.mcpServer.saveAllowlist")}
</Button>
</div>
</form>
{error ? (
<div className="flex items-center gap-2">
<p role="alert" className="text-destructive text-sm">
{t("settings.readFailed", { message: localizedError(error, t) })}
</p>
<Button type="button" variant="outline" size="sm" onClick={load}>
{t("settings.reload")}
</Button>
</div>
) : null}
<div className="flex flex-col gap-2">
<div className="flex items-center justify-between gap-2">
<span className="font-medium text-sm">{t("settings.mcpServer.tokens")}</span>
<Button type="button" size="sm" disabled={!settings} onClick={openCreate}>
<PlusIcon />
{t("settings.mcpServer.newToken")}
</Button>
</div>
{tokens.length === 0 ? (
<p className="text-muted-foreground text-sm">{t("settings.mcpServer.noTokens")}</p>
) : (
<ul className="flex flex-col divide-y rounded-lg border">
{tokens.map((token) => {
const status = tokenStatus(token);
return (
<li key={token.id} className="flex flex-wrap items-start justify-between gap-3 p-3">
<div className="flex min-w-0 flex-col gap-1">
<div className="flex flex-wrap items-center gap-2">
<span className="truncate font-medium text-sm">{token.name}</span>
<Badge variant={status === "active" ? "secondary" : "destructive"}>
{t(`settings.mcpServer.status.${status}`)}
</Badge>
<code className="text-muted-foreground text-xs">{token.token_prefix}…</code>
</div>
<div className="flex flex-wrap gap-1">
{SCOPES.filter((scope) => token.scopes.includes(scope.value)).map((scope) => (
<Badge key={scope.value} variant="outline">
{t(`settings.mcpServer.scope.${scope.key}`)}
</Badge>
))}
<Badge variant="outline">
{token.company_ids.length === 0
? t("settings.mcpServer.allCompanies")
: t("settings.mcpServer.companyCount", { n: token.company_ids.length })}
</Badge>
</div>
<p className="text-muted-foreground text-xs">
{token.last_used_at
? t("settings.mcpServer.lastUsed", { time: formatTime(token.last_used_at, locale) })
: t("settings.mcpServer.neverUsed")}
{" · "}
{token.expires_at
? t("settings.mcpServer.expires", { time: formatTime(token.expires_at, locale) })
: t("settings.mcpServer.neverExpires")}
</p>
{token.scopes.includes("task:create") ? (
<p className="text-muted-foreground text-xs">
{t("settings.mcpServer.limits", {
active: limit(token.max_active_tasks),
hourly: limit(token.max_tasks_per_hour),
})}
</p>
) : null}
</div>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => setConfirm({ action: status === "active" ? "revoke" : "delete", token })}
>
{status === "active" ? t("settings.mcpServer.revoke") : t("settings.mcpServer.delete")}
</Button>
</li>
);
})}
</ul>
)}
</div>
<div className="flex flex-col gap-2">
<div className="flex items-center justify-between gap-2">
<div>
<span className="font-medium text-sm">{t("settings.mcpServer.audit")}</span>
<p className="text-muted-foreground text-xs">{t("settings.mcpServer.auditHelp")}</p>
</div>
<Button type="button" variant="outline" size="sm" onClick={load}>
<RefreshCwIcon />
{t("settings.mcpServer.refresh")}
</Button>
</div>
{audit.length === 0 ? (
<p className="text-muted-foreground text-sm">{t("settings.mcpServer.noAudit")}</p>
) : (
<ul className="flex max-h-80 flex-col divide-y overflow-y-auto rounded-lg border">
{audit.map((entry) => (
<li key={entry.id} className="flex flex-col gap-1 p-3 text-xs">
<div className="flex flex-wrap items-center gap-2">
<Badge variant={entry.ok ? "secondary" : "destructive"}>
{entry.ok ? t("settings.mcpServer.auditOk") : t("settings.mcpServer.auditFailed")}
</Badge>
<code className="font-medium">{entry.tool}</code>
<span className="text-muted-foreground">{entry.token_name}</span>
<span className="text-muted-foreground">{formatTime(entry.created_at, locale)}</span>
<span className="text-muted-foreground">{entry.remote_addr}</span>
</div>
<code className="break-all text-muted-foreground">{entry.args}</code>
{entry.ok ? null : <span className="break-all text-destructive">{entry.result}</span>}
</li>
))}
</ul>
)}
</div>
</FieldGroup>
</CardContent>
<Dialog open={createOpen} onOpenChange={setCreateOpen}>
<DialogContent className="max-h-[90vh] overflow-y-auto">
<form onSubmit={create} className="flex flex-col gap-4">
<DialogHeader>
<DialogTitle>{t("settings.mcpServer.createTitle")}</DialogTitle>
<DialogDescription>{t("settings.mcpServer.createHelp")}</DialogDescription>
</DialogHeader>
<FieldGroup>
<Field>
<FieldLabel htmlFor="mcp-token-name">{t("settings.mcpServer.name")}</FieldLabel>
<Input
id="mcp-token-name"
required
maxLength={80}
value={form.name}
placeholder={t("settings.mcpServer.namePlaceholder")}
onChange={(e) => setForm({ ...form, name: e.target.value })}
/>
</Field>
<Field>
<FieldLabel>{t("settings.mcpServer.scopes")}</FieldLabel>
{SCOPES.map((scope) => (
<label
key={scope.value}
htmlFor={`mcp-scope-${scope.key}`}
className="flex items-start gap-2 text-sm"
>
<Checkbox
id={`mcp-scope-${scope.key}`}
className="mt-0.5"
checked={form.scopes.includes(scope.value)}
onCheckedChange={(on) =>
setForm({ ...form, scopes: toggleIn(form.scopes, scope.value, on === true) })
}
/>
<span>
{t(`settings.mcpServer.scope.${scope.key}`)}
<span className="block text-muted-foreground text-xs">
{t(`settings.mcpServer.scopeHelp.${scope.key}`)}
</span>
</span>
</label>
))}
</Field>
<Field>
<FieldLabel>{t("settings.mcpServer.companies")}</FieldLabel>
{companies.length === 0 ? (
<p className="text-muted-foreground text-sm">{t("settings.mcpServer.noCompanies")}</p>
) : (
<div className="flex max-h-40 flex-col gap-2 overflow-y-auto rounded-lg border p-2">
{companies.map((company) => (
<label
key={company.id}
htmlFor={`mcp-company-${company.id}`}
className="flex items-center gap-2 text-sm"
>
<Checkbox
id={`mcp-company-${company.id}`}
checked={form.companyIds.includes(company.id)}
onCheckedChange={(on) =>
setForm({ ...form, companyIds: toggleIn(form.companyIds, company.id, on === true) })
}
/>
<span className="truncate">{company.name}</span>
</label>
))}
</div>
)}
<FieldDescription>{t("settings.mcpServer.companiesHelp")}</FieldDescription>
</Field>
<Field>
<FieldLabel htmlFor="mcp-token-days">{t("settings.mcpServer.expiry")}</FieldLabel>
<Input
id="mcp-token-days"
type="number"
min={0}
max={3650}
value={form.days}
onChange={(e) => setForm({ ...form, days: e.target.value })}
/>
<FieldDescription>{t("settings.mcpServer.expiryHelp")}</FieldDescription>
</Field>
{form.scopes.includes("task:create") ? (
<>
<Field>
<FieldLabel htmlFor="mcp-token-active">{t("settings.mcpServer.maxActive")}</FieldLabel>
<Input
id="mcp-token-active"
type="number"
min={0}
max={10000}
value={form.maxActive}
onChange={(e) => setForm({ ...form, maxActive: e.target.value })}
/>
<FieldDescription>{t("settings.mcpServer.maxActiveHelp")}</FieldDescription>
</Field>
<Field>
<FieldLabel htmlFor="mcp-token-hourly">{t("settings.mcpServer.maxHourly")}</FieldLabel>
<Input
id="mcp-token-hourly"
type="number"
min={0}
max={10000}
value={form.maxHourly}
onChange={(e) => setForm({ ...form, maxHourly: e.target.value })}
/>
<FieldDescription>{t("settings.mcpServer.maxHourlyHelp")}</FieldDescription>
</Field>
</>
) : null}
{createError ? (
<p role="alert" className="text-destructive text-sm">
{t("settings.saveFailed", { message: localizedError(createError, t) })}
</p>
) : null}
</FieldGroup>
<DialogFooter>
<Button type="button" variant="outline" onClick={() => setCreateOpen(false)}>
{t("settings.mcpServer.cancel")}
</Button>
<Button type="submit" disabled={creating || form.scopes.length === 0}>
{creating ? t("settings.mcpServer.creating") : t("settings.mcpServer.create")}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
<Dialog open={createdToken !== null} onOpenChange={(open) => (open ? null : setCreatedToken(null))}>
<DialogContent>
<DialogHeader>
<DialogTitle>{t("settings.mcpServer.createdTitle")}</DialogTitle>
<DialogDescription>{t("settings.mcpServer.createdHelp")}</DialogDescription>
</DialogHeader>
<div className="flex gap-2">
<Input readOnly value={createdToken ?? ""} className="font-mono text-xs" />
<Button type="button" variant="outline" onClick={() => copy(createdToken ?? "")}>
<CopyIcon />
{t("settings.mcpServer.copy")}
</Button>
</div>
<DialogFooter>
<Button type="button" onClick={() => setCreatedToken(null)}>
{t("settings.mcpServer.done")}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<AlertDialog open={confirm !== null} onOpenChange={(open) => (open ? null : setConfirm(null))}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>
{confirm?.action === "delete" ? t("settings.mcpServer.delete") : t("settings.mcpServer.revoke")}
</AlertDialogTitle>
<AlertDialogDescription>
{confirm
? t(
confirm.action === "delete"
? "settings.mcpServer.deleteConfirm"
: "settings.mcpServer.revokeConfirm",
{ name: confirm.token.name },
)
: null}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>{t("settings.mcpServer.cancel")}</AlertDialogCancel>
<AlertDialogAction onClick={runConfirmed}>
{confirm?.action === "delete" ? t("settings.mcpServer.delete") : t("settings.mcpServer.revoke")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</Card>
);
}
@@ -31,6 +31,7 @@ import type { EgressReport, LLMProfile, ProxyPoolEntry, Settings, WorkerPool } f
import { useEgressIp } from "../../_components/egress-ip-banner";
import { BasicAuthCard } from "./_components/basic-auth-card";
import { McpServerCard } from "./_components/mcp-server-card";
import { UpdateCard } from "./_components/update-card";
export default function SystemSettingsPage() {
@@ -766,6 +767,7 @@ export default function SystemSettingsPage() {
<div className="flex flex-col divide-y rounded-xl border bg-card/30 px-3 [&>[data-slot=card]]:mb-0 [&>[data-slot=card]]:rounded-none [&>[data-slot=card]]:bg-transparent [&>[data-slot=card]]:py-4 [&>[data-slot=card]]:ring-0">
{isSettingVisible("system", "settings.keywords.update") ? <UpdateCard /> : null}
{isSettingVisible("system", "settings.keywords.basicAuth") ? <BasicAuthCard /> : null}
{isSettingVisible("system", "settings.keywords.mcpServer") ? <McpServerCard /> : null}
<Card
className={`${isSettingVisible("traffic", "settings.keywords.trafficCapture") ? "" : "hidden"} mb-4 break-inside-avoid md:mb-6`}
+128
View File
@@ -114,6 +114,10 @@ export const settingsMessages = {
"基础认证 登录 用户名 密码",
"basic auth authentication sign-in login username password",
],
"settings.keywords.mcpServer": [
"MCP 服务端 访问令牌 token 智能体 编排 外部 bot 审计 白名单 来源 IP",
"mcp server access token agent orchestration external bot audit allowlist whitelist source ip",
],
"settings.trafficCapture": ["流量捕获", "Traffic capture"],
"settings.trafficCaptureHelp": [
"开启后,所有 Agent 的 HTTP 流量经记录代理全量落库,并向 Agent 注入 traffic_search / traffic_get 工具与代理配置(提示词含代理说明)。",
@@ -476,7 +480,131 @@ export const settingsMessages = {
"保存不会中断当前浏览器访问。可用无痕窗口检查验证弹窗;浏览器可能缓存凭据。关闭后保留账号密码,便于再次开启。",
"Saving does not interrupt access in this browser. Use a private window to check the credential prompt; browsers may cache credentials. Disabling authentication keeps the credentials for future use.",
],
"settings.basicAuthMcpNote": [
"MCP 服务端的 /mcp 端点不受此验证保护,也不能用这里的账号密码访问:它只认访问令牌。",
"The MCP server endpoint /mcp is not covered by this gate and cannot be opened with these credentials: it accepts access tokens only.",
],
"settings.saveBasicAuth": ["保存访问验证", "Save access authentication"],
"settings.mcpServer.title": ["MCP 服务端", "MCP server"],
"settings.mcpServer.help": [
"开启后,外部智能体可通过 MCP 连接 ARTEX:查看任务与漏洞、创建任务、暂停或恢复任务。默认关闭。创建任务会对目标发起真实测试,请只把令牌交给可信的智能体。",
"When enabled, external agents can connect to ARTEX over MCP to view tasks and findings, create tasks, and pause or resume them. Disabled by default. Creating a task starts real testing against a target, so give tokens only to agents you trust.",
],
"settings.mcpServer.enable": ["启用 MCP 服务端", "Enable MCP server"],
"settings.mcpServer.enabled": ["MCP 服务端已开启", "MCP server enabled"],
"settings.mcpServer.disabled": ["MCP 服务端已关闭", "MCP server disabled"],
"settings.mcpServer.endpoint": ["接入地址", "Endpoint"],
"settings.mcpServer.endpointHelp": [
"传输方式为 Streamable HTTP。在智能体里填入此地址,并设置请求头 Authorization: Bearer <访问令牌>。",
"Transport is Streamable HTTP. Enter this URL in your agent and set the header Authorization: Bearer <access token>.",
],
"settings.mcpServer.noBasicAuth": [
"无法使用 HTTP Basic Auth:/mcp 不经过 Basic Auth 验证,也不接受 Basic 账号密码或 ARTEX 登录密码,只能用访问令牌。",
"HTTP Basic Auth cannot be used: /mcp is not behind the Basic Auth gate and does not accept Basic credentials or your ARTEX password. Access tokens are the only way in.",
],
"settings.mcpServer.basicAuthOn": [
"当前已启用 HTTP Basic Auth,/mcp 仍可直接凭访问令牌访问。",
"HTTP Basic Auth is currently enabled; /mcp remains reachable with an access token alone.",
],
"settings.mcpServer.allowlist": ["来源白名单", "Source allowlist"],
"settings.mcpServer.allowlistHelp": [
"只有这些来源地址能调用 /mcp,每行一个 IP 或 CIDR(如 203.0.113.7 或 10.0.0.0/8)。留空 = 不限制来源。白名单在令牌之前检查:不在名单内的来源即使持有有效令牌也会被拒绝(403)。",
"Only these source addresses may call /mcp. One IP or CIDR per line (for example 203.0.113.7 or 10.0.0.0/8). Leave empty for no source restriction. The allowlist is checked before the token: a source that is not listed is rejected (403) even with a valid token.",
],
"settings.mcpServer.allowlistPlaceholder": ["留空 = 不限制来源", "Empty = no source restriction"],
"settings.mcpServer.trustedProxies": ["可信代理", "Trusted proxies"],
"settings.mcpServer.trustedProxiesHelp": [
"ARTEX 部署在反向代理(nginx 等)之后时,填写代理的地址,每行一个 IP 或 CIDR;来自这些地址的请求改用 X-Forwarded-For 里的地址作为来源。不填则一律以直连地址为准——此时经代理进来的请求来源都是代理本身。不要填不受你控制的地址,否则对方可以伪造来源。",
"If ARTEX runs behind a reverse proxy (nginx and the like), list the proxy addresses here, one IP or CIDR per line; requests from them use the address in X-Forwarded-For as the source. Left empty, the direct connection address is always used, so every request arriving through a proxy appears to come from the proxy itself. Never list addresses you do not control, or their owner can forge the source.",
],
"settings.mcpServer.trustedProxiesPlaceholder": ["没有反向代理则留空", "Leave empty without a reverse proxy"],
"settings.mcpServer.clientIp": [
"服务器看到的你当前的来源地址:{{ip}}",
"Your current source address as the server sees it: {{ip}}",
],
"settings.mcpServer.saveAllowlist": ["保存来源白名单", "Save source allowlist"],
"settings.mcpServer.allowlistSaved": ["来源白名单已保存", "Source allowlist saved"],
"settings.mcpServer.copy": ["复制", "Copy"],
"settings.mcpServer.copied": ["已复制", "Copied"],
"settings.mcpServer.tokens": ["访问令牌", "Access tokens"],
"settings.mcpServer.newToken": ["新建令牌", "New token"],
"settings.mcpServer.noTokens": ["还没有访问令牌", "No access tokens yet"],
"settings.mcpServer.status.active": ["有效", "Active"],
"settings.mcpServer.status.revoked": ["已吊销", "Revoked"],
"settings.mcpServer.status.expired": ["已过期", "Expired"],
"settings.mcpServer.scope.read": ["只读", "Read"],
"settings.mcpServer.scope.taskCreate": ["创建任务", "Create tasks"],
"settings.mcpServer.scope.taskControl": ["控制任务", "Control tasks"],
"settings.mcpServer.scopeHelp.read": [
"查看任务、进度、漏洞、企业、分类和模型配置",
"View tasks, progress, findings, companies, categories and model profiles",
],
"settings.mcpServer.scopeHelp.taskCreate": ["新建并启动任务", "Create and start tasks"],
"settings.mcpServer.scopeHelp.taskControl": [
"暂停、恢复任务,给任务补充提示",
"Pause and resume tasks, and add hints to them",
],
"settings.mcpServer.allCompanies": ["不限企业", "All companies"],
"settings.mcpServer.companyCount": ["限定 {{n}} 个企业", "Restricted to {{n}} companies"],
"settings.mcpServer.lastUsed": ["最近使用:{{time}}", "Last used: {{time}}"],
"settings.mcpServer.neverUsed": ["从未使用", "Never used"],
"settings.mcpServer.expires": ["过期:{{time}}", "Expires: {{time}}"],
"settings.mcpServer.neverExpires": ["永不过期", "Never expires"],
"settings.mcpServer.limits": [
"未结束任务上限 {{active}} · 每小时建任务上限 {{hourly}}",
"Unfinished task limit {{active}} · tasks per hour limit {{hourly}}",
],
"settings.mcpServer.unlimited": ["不限", "none"],
"settings.mcpServer.revoke": ["吊销", "Revoke"],
"settings.mcpServer.revoked": ["令牌已吊销", "Token revoked"],
"settings.mcpServer.revokeConfirm": [
"吊销令牌「{{name}}」?使用它的智能体会立即失去访问权限,且无法恢复。",
"Revoke token “{{name}}”? Agents using it lose access immediately and it cannot be restored.",
],
"settings.mcpServer.delete": ["删除", "Delete"],
"settings.mcpServer.deleted": ["令牌已删除", "Token deleted"],
"settings.mcpServer.deleteConfirm": [
"删除令牌「{{name}}」?它的调用审计会保留。",
"Delete token “{{name}}”? Its audit records are kept.",
],
"settings.mcpServer.cancel": ["取消", "Cancel"],
"settings.mcpServer.createTitle": ["新建访问令牌", "New access token"],
"settings.mcpServer.createHelp": [
"令牌只在创建后显示一次,请立即保存。",
"The token is shown only once after creation. Save it right away.",
],
"settings.mcpServer.name": ["名称", "Name"],
"settings.mcpServer.namePlaceholder": ["例如:我的个人助手", "For example: my personal assistant"],
"settings.mcpServer.scopes": ["权限范围", "Permissions"],
"settings.mcpServer.companies": ["限定企业", "Restrict to companies"],
"settings.mcpServer.companiesHelp": [
"不勾选 = 不限。勾选后,令牌只能在这些企业下创建任务(且目标须属于这些企业的范围),也只能看到和控制这些企业下的任务。",
"Leave all unchecked for no restriction. Otherwise the token can create tasks only under these companies (and only for targets in their scope), and can see and control only their tasks.",
],
"settings.mcpServer.noCompanies": ["还没有企业", "No companies yet"],
"settings.mcpServer.expiry": ["有效期(天)", "Valid for (days)"],
"settings.mcpServer.expiryHelp": ["0 = 永不过期", "0 = never expires"],
"settings.mcpServer.maxActive": ["未结束任务上限", "Unfinished task limit"],
"settings.mcpServer.maxActiveHelp": [
"此令牌创建的、尚未结束的任务数上限(含暂停和排队)。0 = 不限",
"Maximum number of unfinished tasks created by this token, including paused and queued ones. 0 = no limit",
],
"settings.mcpServer.maxHourly": ["每小时建任务上限", "Tasks per hour limit"],
"settings.mcpServer.maxHourlyHelp": ["0 = 不限", "0 = no limit"],
"settings.mcpServer.create": ["创建", "Create"],
"settings.mcpServer.creating": ["创建中…", "Creating…"],
"settings.mcpServer.createdTitle": ["令牌已创建", "Token created"],
"settings.mcpServer.createdHelp": [
"这是唯一一次显示完整令牌。关闭后无法再查看,丢失只能吊销后重建。",
"This is the only time the full token is shown. It cannot be viewed again after closing; if lost, revoke it and create a new one.",
],
"settings.mcpServer.done": ["我已保存", "I have saved it"],
"settings.mcpServer.audit": ["调用审计", "Call audit"],
"settings.mcpServer.auditHelp": ["最近 50 次工具调用", "Most recent 50 tool calls"],
"settings.mcpServer.noAudit": ["还没有调用记录", "No calls recorded yet"],
"settings.mcpServer.auditOk": ["成功", "OK"],
"settings.mcpServer.auditFailed": ["失败", "Failed"],
"settings.mcpServer.refresh": ["刷新", "Refresh"],
"settings.reload": ["重新加载", "Reload"],
"settings.updateNetworkLoadFailedPrefix": ["读取更新网络设置失败:", "Could not load update network settings: "],
"settings.updateCheckFailedPrefix": ["检查更新失败:", "Could not check for updates: "],
+62
View File
@@ -163,6 +163,54 @@ export async function apiFetch(input: string, init?: RequestInit): Promise<Respo
return response;
}
export type McpServerScope = "read" | "task:create" | "task:control";
export interface McpServerSettings {
enabled: boolean;
path: string;
basic_auth_enabled: boolean;
allowed_ips: string[];
trusted_proxies: string[];
// 服务端按 /mcp 的同一套规则解析出的、当前管理员请求的来源地址。
client_ip?: string;
}
export interface McpServerToken {
id: number;
name: string;
token_prefix: string;
scopes: McpServerScope[];
company_ids: number[];
max_active_tasks: number;
max_tasks_per_hour: number;
expires_at: string | null;
last_used_at: string | null;
revoked_at: string | null;
created_at: string;
}
export interface McpServerTokenInput {
name: string;
scopes: McpServerScope[];
company_ids: number[];
max_active_tasks: number;
max_tasks_per_hour: number;
expires_in_days: number;
}
export interface McpServerAuditEntry {
id: number;
token_id: number;
token_name: string;
tool: string;
args: string;
ok: boolean;
result: string;
remote_addr: string;
duration_ms: number;
created_at: string;
}
export class ApiError extends Error {
constructor(
message: string,
@@ -1100,6 +1148,20 @@ export const api = {
setBasicAuthSettings: (settings: { enabled: boolean; username: string; password: string }) =>
put<{ enabled: boolean; username: string; password_set: boolean }>("/settings/basic-auth", settings),
setSettings: (patch: Partial<Settings>) => put<Settings>(`/settings`, patch),
// ---- MCP 服务端(ARTEX 对外暴露的 /mcp):开关、访问令牌、调用审计 ----
mcpServerSettings: () => get<McpServerSettings>("/mcp-server/settings"),
setMcpServerEnabled: (enabled: boolean) => put<McpServerSettings>("/mcp-server/settings", { enabled }),
setMcpServerAccess: (access: { allowed_ips: string[]; trusted_proxies: string[] }) =>
put<McpServerSettings>("/mcp-server/settings", access),
mcpServerTokens: () => get<{ tokens: McpServerToken[] }>("/mcp-server/tokens").then((r) => arr(r.tokens)),
// 明文令牌只在创建响应里返回这一次。
createMcpServerToken: (input: McpServerTokenInput) =>
post<{ token: string; item: McpServerToken }>("/mcp-server/tokens", input),
revokeMcpServerToken: (id: number) => post<{ ok: boolean }>(`/mcp-server/tokens/${id}/revoke`),
deleteMcpServerToken: (id: number) => del<{ ok: boolean }>(`/mcp-server/tokens/${id}`),
mcpServerAudit: (limit = 50) =>
get<{ entries: McpServerAuditEntry[] }>(`/mcp-server/audit?limit=${limit}`).then((r) => arr(r.entries)),
// Run a real "test" search with the given (or saved) config to verify it works.
testWebSearch: (patch: {
web_search_backend?: string;