Junjie
9 天以前 9a8018c3fbc94f99d5d184c8cb1ef23d7366cea0
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
package com.zy.ai.mcp.tool;
 
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zy.ai.domain.autotune.AutoTuneApplyRequest;
import com.zy.ai.domain.autotune.AutoTuneApplyResult;
import com.zy.ai.domain.autotune.AutoTuneChangeCommand;
import com.zy.ai.domain.autotune.AutoTuneSnapshot;
import com.zy.ai.entity.AiAutoTuneChange;
import com.zy.ai.entity.AiAutoTuneJob;
import com.zy.ai.entity.AiAutoTuneMcpCall;
import com.zy.ai.enums.AiPromptScene;
import com.zy.ai.service.AiAutoTuneChangeService;
import com.zy.ai.service.AiAutoTuneJobService;
import com.zy.ai.service.AiAutoTuneMcpCallService;
import com.zy.ai.service.AutoTuneApplyService;
import com.zy.ai.service.AutoTuneSnapshotService;
import com.zy.ai.utils.AutoTuneWriteBehaviorUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.stereotype.Component;
 
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.LongSupplier;
 
@Component
@RequiredArgsConstructor
public class AutoTuneMcpTools {
 
    private static final int DEFAULT_RECENT_JOB_LIMIT = 5;
    private static final int MAX_RECENT_JOB_LIMIT = 20;
    private static final long DRY_RUN_TOKEN_TTL_MILLIS = 10L * 60L * 1000L;
 
    private final AutoTuneSnapshotService autoTuneSnapshotService;
    private final AutoTuneApplyService autoTuneApplyService;
    private final AiAutoTuneJobService aiAutoTuneJobService;
    private final AiAutoTuneChangeService aiAutoTuneChangeService;
    private final AiAutoTuneMcpCallService aiAutoTuneMcpCallService;
    private final ConcurrentMap<String, DryRunPreview> dryRunPreviews = new ConcurrentHashMap<>();
    private LongSupplier currentTimeMillisSupplier = System::currentTimeMillis;
 
    @Tool(name = "dispatch_get_auto_tune_snapshot", description = "获取WCS自动调参所需的调度快照、站点运行态、拓扑容量、当前可写参数和调参规则约束")
    public AutoTuneSnapshot getAutoTuneSnapshot() {
        return autoTuneSnapshotService.buildSnapshot();
    }
 
    @Tool(name = "dispatch_get_recent_auto_tune_jobs", description = "获取近期自动调参任务摘要及其变更结果,默认5条,最大20条")
    public List<Map<String, Object>> getRecentAutoTuneJobs(
            @ToolParam(description = "返回任务数量上限,默认5,最大20", required = false) Integer limit) {
        int safeLimit = boundLimit(limit);
        List<AiAutoTuneJob> jobs = aiAutoTuneJobService.list(new QueryWrapper<AiAutoTuneJob>()
                .eq("prompt_scene_code", AiPromptScene.AUTO_TUNE_DISPATCH.getCode())
                .orderByDesc("start_time")
                .orderByDesc("id")
                .last("limit " + safeLimit));
        if (jobs == null || jobs.isEmpty()) {
            return new ArrayList<>();
        }
 
        List<Map<String, Object>> result = new ArrayList<>();
        for (AiAutoTuneJob job : jobs) {
            result.add(toJobSummary(job));
        }
        return result;
    }
 
    @Tool(name = "dispatch_apply_auto_tune_changes", description = "提交自动调参变更。实际应用前必须先使用 dryRun=true 验证")
    public AutoTuneApplyResult applyAutoTuneChanges(
            @ToolParam(description = "本次调参原因或分析摘要", required = false) String reason,
            @ToolParam(description = "建议自动调参分析间隔分钟", required = false) Integer analysisIntervalMinutes,
            @ToolParam(description = "触发类型,例如 scheduler/manual/agent", required = false) String triggerType,
            @ToolParam(description = "是否仅试算,实际应用前必须先传 true", required = false) Boolean dryRun,
            @ToolParam(description = "dry-run 成功后返回的预览令牌。dryRun=false 时必须提供,且变更集必须完全一致", required = false) String dryRunToken,
            @ToolParam(description = "调参变更列表") List<AutoTuneChangeCommand> changes) {
        if (dryRun == null) {
            throw new IllegalArgumentException("dryRun is required. Use dryRun=true first to create a preview token.");
        }
 
        AutoTuneApplyRequest request = new AutoTuneApplyRequest();
        request.setReason(reason);
        request.setAnalysisIntervalMinutes(analysisIntervalMinutes);
        request.setTriggerType(triggerType);
        request.setDryRun(dryRun);
        request.setChanges(changes);
 
        String fingerprint = buildChangeFingerprint(changes);
        if (Boolean.FALSE.equals(dryRun)) {
            requireMatchingDryRunToken(dryRunToken, fingerprint);
        }
 
        AutoTuneApplyResult result = autoTuneApplyService.apply(request);
        if (Boolean.TRUE.equals(dryRun) && hasApplicableDryRunChanges(result)) {
            result.setDryRunToken(createDryRunToken(fingerprint));
        }
        return result;
    }
 
    @Tool(name = "dispatch_revert_last_auto_tune_job", description = "回滚最近一次成功的自动调参任务")
    public AutoTuneApplyResult revertLastAutoTuneJob(
            @ToolParam(description = "回滚原因,必须说明来自MCP事实的异常证据", required = false) String reason) {
        return autoTuneApplyService.rollbackLastSuccessfulJob(reason);
    }
 
    private Map<String, Object> toJobSummary(AiAutoTuneJob job) {
        LinkedHashMap<String, Object> item = new LinkedHashMap<>();
        item.put("id", job.getId());
        item.put("triggerType", job.getTriggerType());
        item.put("status", job.getStatus());
        item.put("startTime", job.getStartTime());
        item.put("finishTime", job.getFinishTime());
        item.put("summary", job.getSummary());
        item.put("successCount", job.getSuccessCount());
        item.put("rejectCount", job.getRejectCount());
        item.put("errorMessage", job.getErrorMessage());
        List<AiAutoTuneMcpCall> mcpCalls = listMcpCalls(job.getId());
        List<Map<String, Object>> mcpCallSummaries = toMcpCallSummaries(mcpCalls);
        List<Map<String, Object>> changeSummaries = listChangeSummaries(job, mcpCalls);
        AutoTuneWriteBehaviorUtils.addWriteBehavior(item,
                AutoTuneWriteBehaviorUtils.resolveJobWriteBehavior(job, mcpCallSummaries, changeSummaries));
        item.put("mcpCallCount", mcpCalls.size());
        item.put("mcpCalls", mcpCallSummaries);
        item.put("changes", changeSummaries);
        return item;
    }
 
    private List<AiAutoTuneMcpCall> listMcpCalls(Long agentJobId) {
        if (agentJobId == null) {
            return new ArrayList<>();
        }
        List<AiAutoTuneMcpCall> mcpCalls = aiAutoTuneMcpCallService.list(new QueryWrapper<AiAutoTuneMcpCall>()
                .eq("agent_job_id", agentJobId)
                .orderByAsc("call_seq")
                .orderByAsc("id"));
        return mcpCalls == null ? new ArrayList<>() : mcpCalls;
    }
 
    private List<Map<String, Object>> toMcpCallSummaries(List<AiAutoTuneMcpCall> mcpCalls) {
        List<Map<String, Object>> result = new ArrayList<>();
        if (mcpCalls == null || mcpCalls.isEmpty()) {
            return result;
        }
        for (AiAutoTuneMcpCall mcpCall : mcpCalls) {
            result.add(toMcpCallSummary(mcpCall));
        }
        return result;
    }
 
    private Map<String, Object> toMcpCallSummary(AiAutoTuneMcpCall mcpCall) {
        LinkedHashMap<String, Object> item = new LinkedHashMap<>();
        item.put("callSeq", mcpCall.getCallSeq());
        item.put("toolName", mcpCall.getToolName());
        item.put("status", mcpCall.getStatus());
        item.put("dryRun", toBoolean(mcpCall.getDryRun()));
        item.put("applyJobId", mcpCall.getApplyJobId());
        item.put("successCount", mcpCall.getSuccessCount());
        item.put("rejectCount", mcpCall.getRejectCount());
        item.put("errorMessage", mcpCall.getErrorMessage());
        AutoTuneWriteBehaviorUtils.addWriteBehavior(item,
                AutoTuneWriteBehaviorUtils.resolveMcpWriteBehavior(mcpCall));
        return item;
    }
 
    private Boolean toBoolean(Integer value) {
        if (value == null) {
            return null;
        }
        return value == 1;
    }
 
    private List<Map<String, Object>> listChangeSummaries(AiAutoTuneJob job, List<AiAutoTuneMcpCall> mcpCalls) {
        Map<Long, String> ownerTriggerTypes = collectChangeOwnerTriggerTypes(job, mcpCalls);
        List<Long> applyJobIds = new ArrayList<>(ownerTriggerTypes.keySet());
        if (applyJobIds.isEmpty()) {
            return new ArrayList<>();
        }
        List<AiAutoTuneChange> changes = aiAutoTuneChangeService.list(new QueryWrapper<AiAutoTuneChange>()
                .in("job_id", applyJobIds)
                .orderByAsc("job_id")
                .orderByAsc("id"));
        if (changes == null || changes.isEmpty()) {
            return new ArrayList<>();
        }
 
        List<Map<String, Object>> result = new ArrayList<>();
        for (AiAutoTuneChange change : changes) {
            result.add(toChangeSummary(change, ownerTriggerTypes.get(change.getJobId())));
        }
        return result;
    }
 
    private Map<Long, String> collectChangeOwnerTriggerTypes(AiAutoTuneJob job, List<AiAutoTuneMcpCall> mcpCalls) {
        LinkedHashMap<Long, String> result = new LinkedHashMap<>();
        if (job != null && job.getId() != null) {
            result.put(job.getId(), job.getTriggerType());
        }
        if (mcpCalls == null || mcpCalls.isEmpty()) {
            return result;
        }
        for (AiAutoTuneMcpCall mcpCall : mcpCalls) {
            Long applyJobId = mcpCall.getApplyJobId();
            if (applyJobId == null || result.containsKey(applyJobId)) {
                continue;
            }
            result.put(applyJobId, resolveMcpApplyJobTriggerType(mcpCall));
        }
        return result;
    }
 
    private String resolveMcpApplyJobTriggerType(AiAutoTuneMcpCall mcpCall) {
        if (mcpCall == null || mcpCall.getToolName() == null) {
            return null;
        }
        String toolName = mcpCall.getToolName().toLowerCase(Locale.ROOT);
        return toolName.contains("revert_last_auto_tune_job") || toolName.contains("rollback") ? "rollback" : null;
    }
 
    private Map<String, Object> toChangeSummary(AiAutoTuneChange change, String ownerTriggerType) {
        LinkedHashMap<String, Object> item = new LinkedHashMap<>();
        item.put("jobId", change.getJobId());
        item.put("targetType", change.getTargetType());
        item.put("targetId", change.getTargetId());
        item.put("targetKey", change.getTargetKey());
        item.put("oldValue", change.getOldValue());
        item.put("requestedValue", change.getRequestedValue());
        item.put("appliedValue", change.getAppliedValue());
        item.put("resultStatus", change.getResultStatus());
        item.put("rejectReason", change.getRejectReason());
        item.put("cooldownExpireTime", change.getCooldownExpireTime());
        item.put("createTime", change.getCreateTime());
        AutoTuneWriteBehaviorUtils.addWriteBehavior(item,
                AutoTuneWriteBehaviorUtils.resolveChangeWriteBehavior(change, ownerTriggerType));
        return item;
    }
 
    private int boundLimit(Integer limit) {
        if (limit == null || limit <= 0) {
            return DEFAULT_RECENT_JOB_LIMIT;
        }
        return Math.min(limit, MAX_RECENT_JOB_LIMIT);
    }
 
    private void requireMatchingDryRunToken(String dryRunToken, String fingerprint) {
        cleanExpiredDryRunPreviews();
        if (isBlank(dryRunToken)) {
            throw new IllegalArgumentException("dryRunToken is required when dryRun=false. Run dryRun=true first.");
        }
        DryRunPreview preview = dryRunPreviews.remove(dryRunToken.trim());
        if (preview == null) {
            throw new IllegalArgumentException("dryRunToken is missing, expired, or already used.");
        }
        if (preview.isExpired(currentTimeMillis())) {
            throw new IllegalArgumentException("dryRunToken is expired. Run dryRun=true again.");
        }
        if (!preview.getFingerprint().equals(fingerprint)) {
            throw new IllegalArgumentException("dryRunToken does not match the requested change set.");
        }
    }
 
    private String createDryRunToken(String fingerprint) {
        cleanExpiredDryRunPreviews();
        String token = UUID.randomUUID().toString();
        dryRunPreviews.put(token, new DryRunPreview(fingerprint, currentTimeMillis() + DRY_RUN_TOKEN_TTL_MILLIS));
        return token;
    }
 
    private void cleanExpiredDryRunPreviews() {
        long currentTimeMillis = currentTimeMillis();
        for (Map.Entry<String, DryRunPreview> entry : dryRunPreviews.entrySet()) {
            if (entry.getValue() == null || entry.getValue().isExpired(currentTimeMillis)) {
                dryRunPreviews.remove(entry.getKey());
            }
        }
    }
 
    private boolean isSuccessful(AutoTuneApplyResult result) {
        return result != null && Boolean.TRUE.equals(result.getSuccess());
    }
 
    private boolean hasApplicableDryRunChanges(AutoTuneApplyResult result) {
        if (!isSuccessful(result) || result.getChanges() == null || result.getChanges().isEmpty()) {
            return false;
        }
        for (AiAutoTuneChange change : result.getChanges()) {
            if (change != null && "dry_run".equals(normalizeLower(change.getResultStatus()))) {
                return true;
            }
        }
        return false;
    }
 
    private String buildChangeFingerprint(List<AutoTuneChangeCommand> changes) {
        List<Map<String, String>> normalizedChanges = new ArrayList<>();
        if (changes != null) {
            for (AutoTuneChangeCommand change : changes) {
                normalizedChanges.add(toNormalizedChange(change));
            }
        }
        validateUniqueChangeTargets(normalizedChanges);
        normalizedChanges.sort(Comparator
                .comparing((Map<String, String> item) -> item.get("targetType"))
                .thenComparing(item -> item.get("targetId"))
                .thenComparing(item -> item.get("targetKey"))
                .thenComparing(item -> item.get("newValue")));
        return JSON.toJSONString(normalizedChanges);
    }
 
    private void validateUniqueChangeTargets(List<Map<String, String>> normalizedChanges) {
        Map<String, Map<String, String>> uniqueTargets = new LinkedHashMap<>();
        for (Map<String, String> change : normalizedChanges) {
            String targetSignature = buildTargetSignature(change);
            if (uniqueTargets.containsKey(targetSignature)) {
                throw new IllegalArgumentException("Duplicate auto-tune change target in same request: "
                        + "targetType=" + change.get("targetType")
                        + ", targetId=" + change.get("targetId")
                        + ", targetKey=" + change.get("targetKey"));
            }
            uniqueTargets.put(targetSignature, change);
        }
    }
 
    private String buildTargetSignature(Map<String, String> change) {
        return change.get("targetType") + "\n"
                + change.get("targetId") + "\n"
                + change.get("targetKey");
    }
 
    private Map<String, String> toNormalizedChange(AutoTuneChangeCommand change) {
        LinkedHashMap<String, String> item = new LinkedHashMap<>();
        String targetType = normalizeLower(change == null ? null : change.getTargetType());
        item.put("targetType", targetType);
        item.put("targetId", "sys_config".equals(targetType) ? "" : normalizeText(change == null ? null : change.getTargetId()));
        item.put("targetKey", normalizeText(change == null ? null : change.getTargetKey()));
        item.put("newValue", normalizeText(change == null ? null : change.getNewValue()));
        return item;
    }
 
    private String normalizeLower(String value) {
        return normalizeText(value).toLowerCase(Locale.ROOT);
    }
 
    private String normalizeText(String value) {
        return value == null ? "" : value.trim();
    }
 
    private boolean isBlank(String value) {
        return value == null || value.trim().isEmpty();
    }
 
    private long currentTimeMillis() {
        return currentTimeMillisSupplier.getAsLong();
    }
 
    void setCurrentTimeMillisSupplier(LongSupplier currentTimeMillisSupplier) {
        this.currentTimeMillisSupplier = currentTimeMillisSupplier == null
                ? System::currentTimeMillis
                : currentTimeMillisSupplier;
    }
 
    private static class DryRunPreview {
        private final String fingerprint;
        private final long expireAtMillis;
 
        DryRunPreview(String fingerprint, long expireAtMillis) {
            this.fingerprint = fingerprint;
            this.expireAtMillis = expireAtMillis;
        }
 
        String getFingerprint() {
            return fingerprint;
        }
 
        boolean isExpired(long currentTimeMillis) {
            return currentTimeMillis > expireAtMillis;
        }
    }
}