zhou zhou
2026-03-19 ffbf67765d2ae447d62333eed85100a15685d781
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
import React, { useEffect, useMemo, useState } from "react";
import {
    Accordion,
    AccordionDetails,
    AccordionSummary,
    Alert,
    Box,
    Button,
    Card,
    CardContent,
    CircularProgress,
    Grid,
    MenuItem,
    Stack,
    TextField,
    Typography,
} from "@mui/material";
import PlayCircleOutlineOutlinedIcon from "@mui/icons-material/PlayCircleOutlineOutlined";
import PreviewOutlinedIcon from "@mui/icons-material/PreviewOutlined";
import ExpandMoreOutlinedIcon from "@mui/icons-material/ExpandMoreOutlined";
import { useNotify } from "react-admin";
import { previewMcpTools, testMcpConnectivity, testMcpTool } from "@/api/ai/mcpMount";
 
const parseInputSchema = (inputSchema) => {
    if (!inputSchema) {
        return { pretty: "", fields: [], required: [], error: "" };
    }
    try {
        const schema = JSON.parse(inputSchema);
        const properties = schema?.properties || {};
        const required = Array.isArray(schema?.required) ? schema.required : [];
        return {
            pretty: JSON.stringify(schema, null, 2),
            required,
            error: "",
            fields: Object.entries(properties).map(([name, definition]) => ({
                name,
                title: definition?.title || name,
                description: definition?.description || "",
                type: definition?.type || "string",
                enumValues: Array.isArray(definition?.enum) ? definition.enum : [],
            })),
        };
    } catch (error) {
        return {
            pretty: inputSchema,
            fields: [],
            required: [],
            error: `Input Schema 解析失败: ${error.message}`,
        };
    }
};
 
const normalizeFieldValue = (field, rawValue) => {
    if (rawValue === "" || rawValue == null) {
        return undefined;
    }
    if (field.type === "integer") {
        const parsed = Number.parseInt(rawValue, 10);
        return Number.isNaN(parsed) ? rawValue : parsed;
    }
    if (field.type === "number") {
        const parsed = Number(rawValue);
        return Number.isNaN(parsed) ? rawValue : parsed;
    }
    if (field.type === "boolean") {
        return rawValue === true || rawValue === "true";
    }
    return rawValue;
};
 
const buildInputJson = (schemaInfo, fieldValues) => {
    if (!schemaInfo?.fields?.length) {
        return "";
    }
    const payload = {};
    schemaInfo.fields.forEach((field) => {
        const normalized = normalizeFieldValue(field, fieldValues?.[field.name]);
        if (normalized !== undefined) {
            payload[field.name] = normalized;
        }
    });
    return JSON.stringify(payload, null, 2);
};
 
const readStructuredValues = (schemaInfo, inputJson) => {
    if (!schemaInfo?.fields?.length || !inputJson || !inputJson.trim()) {
        return {};
    }
    try {
        const parsed = JSON.parse(inputJson);
        if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
            return {};
        }
        const values = {};
        schemaInfo.fields.forEach((field) => {
            const value = parsed[field.name];
            if (value === undefined || value === null) {
                return;
            }
            values[field.name] = typeof value === "boolean" ? String(value) : String(value);
        });
        return values;
    } catch (error) {
        return {};
    }
};
 
const resolveConnectivitySeverity = (healthStatus) => {
    if (healthStatus === "HEALTHY") {
        return "success";
    }
    if (healthStatus === "UNHEALTHY") {
        return "error";
    }
    return "info";
};
 
const AiMcpMountToolsPanel = ({ mountId }) => {
    const notify = useNotify();
    const [loading, setLoading] = useState(false);
    const [tools, setTools] = useState([]);
    const [error, setError] = useState("");
    const [inputs, setInputs] = useState({});
    const [structuredInputs, setStructuredInputs] = useState({});
    const [outputs, setOutputs] = useState({});
    const [testingToolName, setTestingToolName] = useState("");
    const [testingConnectivity, setTestingConnectivity] = useState(false);
    const [connectivity, setConnectivity] = useState(null);
 
    const schemaInfoMap = useMemo(() => {
        return tools.reduce((result, tool) => {
            result[tool.name] = parseInputSchema(tool.inputSchema);
            return result;
        }, {});
    }, [tools]);
 
    useEffect(() => {
        if (!mountId) {
            setTools([]);
            setInputs({});
            setStructuredInputs({});
            setOutputs({});
            setConnectivity(null);
            setError("");
            return;
        }
        loadTools();
    }, [mountId]);
 
    const loadTools = async () => {
        setLoading(true);
        setError("");
        try {
            const data = await previewMcpTools(mountId);
            setTools(data);
            setOutputs({});
            setInputs({});
            setStructuredInputs({});
        } catch (requestError) {
            setError(requestError.message || "获取工具列表失败");
        } finally {
            setLoading(false);
        }
    };
 
    const handleConnectivityTest = async () => {
        setTestingConnectivity(true);
        try {
            const result = await testMcpConnectivity(mountId);
            setConnectivity(result);
            notify(result?.message || "连通性测试完成");
        } catch (requestError) {
            const message = requestError.message || "连通性测试失败";
            notify(message, { type: "error" });
        } finally {
            setTestingConnectivity(false);
        }
    };
 
    const handleInputChange = (toolName, value) => {
        setInputs((prev) => ({
            ...prev,
            [toolName]: value,
        }));
        setStructuredInputs((prev) => ({
            ...prev,
            [toolName]: readStructuredValues(schemaInfoMap[toolName], value),
        }));
    };
 
    const handleStructuredFieldChange = (toolName, fieldName, value) => {
        const schemaInfo = schemaInfoMap[toolName];
        setStructuredInputs((prev) => {
            const nextToolValues = {
                ...(prev[toolName] || {}),
                [fieldName]: value,
            };
            setInputs((prevInputs) => ({
                ...prevInputs,
                [toolName]: buildInputJson(schemaInfo, nextToolValues),
            }));
            return {
                ...prev,
                [toolName]: nextToolValues,
            };
        });
    };
 
    const handleTest = async (toolName) => {
        const inputJson = inputs[toolName];
        if (!inputJson || !inputJson.trim()) {
            notify("请输入工具测试 JSON", { type: "warning" });
            return;
        }
        setTestingToolName(toolName);
        try {
            const result = await testMcpTool(mountId, {
                toolName,
                inputJson,
            });
            setOutputs((prev) => ({
                ...prev,
                [toolName]: result?.output || "",
            }));
            notify(`工具 ${toolName} 测试完成`);
        } catch (requestError) {
            const message = requestError.message || "工具测试失败";
            setOutputs((prev) => ({
                ...prev,
                [toolName]: message,
            }));
            notify(message, { type: "error" });
        } finally {
            setTestingToolName("");
        }
    };
 
    if (!mountId) {
        return (
            <Alert severity="info" sx={{ mt: 2 }}>
                保存挂载后即可预览工具并执行测试。
            </Alert>
        );
    }
 
    return (
        <Box mt={3}>
            <Accordion defaultExpanded={false} sx={{ borderRadius: 3, overflow: "hidden" }}>
                <AccordionSummary expandIcon={<ExpandMoreOutlinedIcon />}>
                    <Box flex={1}>
                        <Typography variant="h6">工具预览与测试</Typography>
                        <Typography variant="body2" color="text.secondary">
                            支持连通性测试、结构化 Schema 预览和按输入参数自动生成测试表单。
                        </Typography>
                    </Box>
                </AccordionSummary>
                <AccordionDetails>
                    <Stack direction="row" justifyContent="space-between" alignItems="center" mb={1.5} flexWrap="wrap" useFlexGap>
                        <Button size="small" startIcon={<PreviewOutlinedIcon />} onClick={loadTools} disabled={loading}>
                            刷新工具
                        </Button>
                        <Button
                            size="small"
                            variant="outlined"
                            startIcon={<PlayCircleOutlineOutlinedIcon />}
                            onClick={handleConnectivityTest}
                            disabled={testingConnectivity}
                        >
                            {testingConnectivity ? "测试中..." : "连通性测试"}
                        </Button>
                    </Stack>
                    {!!connectivity && (
                        <Alert severity={resolveConnectivitySeverity(connectivity.healthStatus)} sx={{ mb: 2 }}>
                            {connectivity.message}
                            {connectivity.initElapsedMs != null && ` · Init ${connectivity.initElapsedMs} ms`}
                            {connectivity.toolCount != null && ` · Tools ${connectivity.toolCount}`}
                            {connectivity.testedAt && ` · ${connectivity.testedAt}`}
                        </Alert>
                    )}
                    {loading && (
                        <Box display="flex" justifyContent="center" py={4}>
                            <CircularProgress size={28} />
                        </Box>
                    )}
                    {!!error && !loading && (
                        <Alert severity="warning" sx={{ mb: 2 }}>
                            {error}
                        </Alert>
                    )}
                    {!loading && !error && !tools.length && (
                        <Alert severity="info">当前挂载未解析出任何工具。</Alert>
                    )}
                    <Grid container spacing={2}>
                        {tools.map((tool) => {
                            const schemaInfo = schemaInfoMap[tool.name] || { pretty: "", fields: [], required: [], error: "" };
                            const structuredValues = structuredInputs[tool.name] || {};
                            return (
                                <Grid item xs={12} key={tool.name}>
                                    <Accordion defaultExpanded={false} sx={{ borderRadius: 3, overflow: "hidden" }}>
                                        <AccordionSummary expandIcon={<ExpandMoreOutlinedIcon />}>
                                            <Stack direction="row" justifyContent="space-between" alignItems="center" spacing={2} width="100%" pr={1}>
                                                <Box>
                                                    <Typography variant="subtitle1">{tool.name}</Typography>
                                                    <Typography variant="body2" color="text.secondary">
                                                        {tool.description || "暂无描述"}
                                                    </Typography>
                                                    {!!tool.toolPurpose && (
                                                        <Typography variant="caption" color="text.secondary" display="block" mt={0.5}>
                                                            用途: {tool.toolPurpose}
                                                        </Typography>
                                                    )}
                                                </Box>
                                                <Stack direction="row" spacing={1} alignItems="center" flexWrap="wrap" useFlexGap>
                                                    {!!tool.toolGroup && (
                                                        <Typography variant="caption" color="text.secondary">
                                                            {tool.toolGroup}
                                                        </Typography>
                                                    )}
                                                    <Typography variant="caption" color="text.secondary">
                                                        {schemaInfo.fields.length} 个参数
                                                    </Typography>
                                                    <Typography variant="caption" color="text.secondary">
                                                        {tool.returnDirect ? "returnDirect" : "normal"}
                                                    </Typography>
                                                </Stack>
                                            </Stack>
                                        </AccordionSummary>
                                        <AccordionDetails>
                                                <Card variant="outlined" sx={{ borderRadius: 3 }}>
                                                <CardContent>
                                                    {!!tool.queryBoundary && (
                                                        <Alert severity="info" sx={{ mb: 2 }}>
                                                            查询边界: {tool.queryBoundary}
                                                        </Alert>
                                                    )}
                                                    {!!tool.exampleQuestions?.length && (
                                                        <Alert severity="success" sx={{ mb: 2 }}>
                                                            <Typography variant="body2" fontWeight={700} mb={0.5}>
                                                                示例提问
                                                            </Typography>
                                                            {tool.exampleQuestions.map((question) => (
                                                                <Typography key={question} variant="body2">
                                                                    {`- ${question}`}
                                                                </Typography>
                                                            ))}
                                                        </Alert>
                                                    )}
                                                    {!!schemaInfo.error && (
                                                        <Alert severity="warning" sx={{ mb: 2 }}>
                                                            {schemaInfo.error}
                                                        </Alert>
                                                    )}
                                                    <TextField
                                                        label="格式化 Input Schema"
                                                        value={schemaInfo.pretty || tool.inputSchema || ""}
                                                        fullWidth
                                                        multiline
                                                        minRows={6}
                                                        maxRows={16}
                                                        InputProps={{ readOnly: true }}
                                                    />
                                                    {!!schemaInfo.fields.length && (
                                                        <Grid container spacing={2} sx={{ mt: 0.5 }}>
                                                            {schemaInfo.fields.map((field) => (
                                                                <Grid item xs={12} md={field.type === "boolean" ? 6 : 12} key={`${tool.name}-${field.name}`}>
                                                                    <TextField
                                                                        select={field.type === "boolean" || field.enumValues.length > 0}
                                                                        type={field.type === "integer" || field.type === "number" ? "number" : "text"}
                                                                        label={`${field.title}${schemaInfo.required.includes(field.name) ? " *" : ""}`}
                                                                        value={structuredValues[field.name] ?? ""}
                                                                        onChange={(event) => handleStructuredFieldChange(tool.name, field.name, event.target.value)}
                                                                        fullWidth
                                                                        helperText={field.description || field.type}
                                                                        sx={{ mt: 2 }}
                                                                    >
                                                                        {field.type === "boolean" && (
                                                                            [
                                                                                <MenuItem key="true" value="true">true</MenuItem>,
                                                                                <MenuItem key="false" value="false">false</MenuItem>,
                                                                            ]
                                                                        )}
                                                                        {field.type !== "boolean" && field.enumValues.map((value) => (
                                                                            <MenuItem key={value} value={String(value)}>
                                                                                {String(value)}
                                                                            </MenuItem>
                                                                        ))}
                                                                    </TextField>
                                                                </Grid>
                                                            ))}
                                                        </Grid>
                                                    )}
                                                    <TextField
                                                        label="测试输入 JSON"
                                                        value={inputs[tool.name] || ""}
                                                        onChange={(event) => handleInputChange(tool.name, event.target.value)}
                                                        fullWidth
                                                        multiline
                                                        minRows={5}
                                                        maxRows={12}
                                                        sx={{ mt: 2 }}
                                                        placeholder='例如:{"code":"A01"}'
                                                    />
                                                    <Stack direction="row" justifyContent="flex-end" mt={1.5}>
                                                        <Button
                                                            variant="contained"
                                                            startIcon={<PlayCircleOutlineOutlinedIcon />}
                                                            onClick={() => handleTest(tool.name)}
                                                            disabled={testingToolName === tool.name}
                                                        >
                                                            {testingToolName === tool.name ? "测试中..." : "执行测试"}
                                                        </Button>
                                                    </Stack>
                                                    <TextField
                                                        label="测试结果"
                                                        value={outputs[tool.name] || ""}
                                                        fullWidth
                                                        multiline
                                                        minRows={5}
                                                        maxRows={16}
                                                        sx={{ mt: 2 }}
                                                        InputProps={{ readOnly: true }}
                                                    />
                                                </CardContent>
                                            </Card>
                                        </AccordionDetails>
                                    </Accordion>
                                </Grid>
                            );
                        })}
                    </Grid>
                </AccordionDetails>
            </Accordion>
        </Box>
    );
};
 
export default AiMcpMountToolsPanel;