feat(mcp): 新增 integration.context.get 身份与能力自检工具 (REQ-20260911-0012)

- 实时取 AkAuthFilter 鉴权上下文(ThreadLocal AuthContext)+ ToolGuard 同源能力计算,不缓存权限
- tenant_id 映射启用作用域编码;principal_type 集中在 IntegrationContextService.resolvePrincipalType
  判定(当前按 token 绑定用户推导 user_delegated,5629 给 agent_api_key 加 principal_type 列后仅改该方法)
- data_scope_version = token_scope 绑定集合最大 modify_time 的 epoch 毫秒,无状态计算
- capability_levels 数据驱动:能力集合含 *.changes.list 工具即具备 SYNC,当前返回 QUERY
- seed-dev.sql operation 作用域白名单加入该工具
This commit is contained in:
xiaoqu
2026-09-11 23:10:19 +08:00
parent 7b69c8668f
commit 795a433f35
6 changed files with 364 additions and 2 deletions
@@ -0,0 +1,130 @@
package me.iiv.agent.mcp;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import me.iiv.agent.entity.svc.AgentApiKey;
import me.iiv.agent.entity.svc.AgentScope;
import me.iiv.agent.entity.svc.TokenScope;
import me.iiv.agent.mapper.svc.AgentScopeMapper;
import me.iiv.agent.mapper.svc.TokenScopeMapper;
import me.iiv.agent.security.AuthContext;
import me.iiv.agent.security.ToolGuard;
import org.springframework.stereotype.Component;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
/**
* integration.context.get 的上下文计算(REQ-20260911-0012)。
* 所有数据每次调用实时取库(token_scope / agent_scope / ToolGuard 同链路),不缓存权限。
*/
@Component
public class IntegrationContextService {
public static final String PRINCIPAL_USER_DELEGATED = "user_delegated";
public static final String PRINCIPAL_TENANT_SERVICE = "tenant_service";
public static final String CAPABILITY_QUERY = "QUERY";
public static final String CAPABILITY_SYNC = "SYNC";
/** 增量同步工具命名约定:出现该后缀即视为具备 SYNC 能力(数据驱动,不硬编码工具清单) */
static final String CHANGES_TOOL_SUFFIX = ".changes.list";
final TokenScopeMapper tokenScopeMapper;
final AgentScopeMapper agentScopeMapper;
final ToolGuard toolGuard;
public IntegrationContextService(TokenScopeMapper tokenScopeMapper, AgentScopeMapper agentScopeMapper,
ToolGuard toolGuard) {
this.tokenScopeMapper = tokenScopeMapper;
this.agentScopeMapper = agentScopeMapper;
this.toolGuard = toolGuard;
}
public Map<String, Object> buildContext(AuthContext ctx) {
Long tokenId = ctx.getTokenId();
List<TokenScope> bindings = tokenScopeMapper.selectList(new LambdaQueryWrapper<TokenScope>()
.eq(TokenScope::getSoftDelete, 0)
.eq(TokenScope::getTokenId, tokenId));
List<AgentScope> scopes = enabledScopes(bindings);
// 与 tools/call 强制校验(GuardedToolCallback → ToolGuard)走同一实时查询,保证一致
Set<String> allowedTools = toolGuard.allowedToolNames(tokenId);
Map<String, Object> result = new LinkedHashMap<>();
result.put("tenant_id", tenantId(scopes));
result.put("principal_type", resolvePrincipalType(ctx));
result.put("subject_id", subjectId(ctx));
result.put("scopes", new ArrayList<>(new TreeSet<>(allowedTools)));
result.put("data_scope_version", dataScopeVersion(bindings));
result.put("capability_levels", capabilityLevels(allowedTools));
result.put("server_time", OffsetDateTime.now().format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));
return result;
}
/**
* 主体类型判定(5629 切换点):agent_api_key 后续会新增 principal_type 列
* (REQ-20260911-0013 的 Flyway),届时只需改本方法为读列。
* 当前按现有数据推导:token 绑定了用户(user_id 非空且人已解析)即 user_delegated,
* 否则 tenant_service(存量 ak 均为 ensure 签发的用户 Token,不会走到该分支)。
*/
String resolvePrincipalType(AuthContext ctx) {
AgentApiKey token = ctx.getToken();
boolean hasUser = ctx.getUser() != null || (token != null && token.getUserId() != null);
return hasUser ? PRINCIPAL_USER_DELEGATED : PRINCIPAL_TENANT_SERVICE;
}
/** 数据权限版本:token_scope 绑定集合的最大 modify_time(空取 create_time)转 epoch 毫秒;无绑定为 0 */
long dataScopeVersion(List<TokenScope> bindings) {
long max = 0L;
for (TokenScope binding : bindings) {
Date time = binding.getModifyTime() != null ? binding.getModifyTime() : binding.getCreateTime();
if (time != null) {
max = Math.max(max, time.getTime());
}
}
return max;
}
/** 能力等级:能力集合内含 *.changes.list 工具 → SYNC;含其他工具 → QUERY;无能力 → 空 */
List<String> capabilityLevels(Collection<String> allowedTools) {
List<String> levels = new ArrayList<>();
if (allowedTools.stream().anyMatch(name -> !name.endsWith(CHANGES_TOOL_SUFFIX))) {
levels.add(CAPABILITY_QUERY);
}
if (allowedTools.stream().anyMatch(name -> name.endsWith(CHANGES_TOOL_SUFFIX))) {
levels.add(CAPABILITY_SYNC);
}
return levels;
}
/** 租户标识 = 启用的作用域编码(排序后逗号拼接);当前签发规则为一作用域一 Token,多绑定时全部列出 */
String tenantId(List<AgentScope> scopes) {
return scopes.stream().map(AgentScope::getCode).sorted().collect(Collectors.joining(","));
}
private Long subjectId(AuthContext ctx) {
if (ctx.getUser() != null) {
return ctx.getUser().getId();
}
return ctx.getToken() == null ? null : ctx.getToken().getUserId();
}
private List<AgentScope> enabledScopes(List<TokenScope> bindings) {
if (bindings.isEmpty()) {
return List.of();
}
List<Long> scopeIds = bindings.stream().map(TokenScope::getScopeId).distinct().collect(Collectors.toList());
return agentScopeMapper.selectList(new LambdaQueryWrapper<AgentScope>()
.eq(AgentScope::getSoftDelete, 0)
.eq(AgentScope::getStatus, 1)
.in(AgentScope::getId, scopeIds));
}
}
@@ -0,0 +1,43 @@
package me.iiv.agent.mcp.tool;
import me.iiv.agent.mcp.IntegrationContextService;
import me.iiv.agent.mcp.ToolObject;
import me.iiv.agent.mcp.XqTool;
import me.iiv.agent.security.AuthContext;
import me.iiv.agent.security.AuthContextHolder;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
* 集成域工具:integration.context.get(REQ-20260911-0012)。
* 身份与能力自检:返回当前 ak 的租户标识、主体类型、能力集合与数据权限版本,
* 数据全部实时取自鉴权上下文与 svc 库绑定关系,不缓存。
*/
@Component
public class IntegrationTools implements ToolObject {
final IntegrationContextService integrationContextService;
public IntegrationTools(IntegrationContextService integrationContextService) {
this.integrationContextService = integrationContextService;
}
@XqTool(category = "integration", kind = "read")
@Tool(name = "integration.context.get", description = "身份与能力自检:返回当前 Token 的集成上下文。"
+ "tenant_id=Token 所属数据域标识(映射启用状态的作用域编码,多个以逗号拼接);"
+ "principal_type=user_delegated(用户委托)或 tenant_service(服务主体);"
+ "subject_id=用户 ID 或服务主体 ID;"
+ "scopes=该 Token 允许调用的工具集合(与 tools/call 强制校验同源实时计算);"
+ "data_scope_version=数据权限版本(token_scope 绑定集合最大修改时间的 epoch 毫秒,无绑定为 0);"
+ "capability_levels=QUERY 或 SYNC(能力集合中含 *.changes.list 工具时具备 SYNC);"
+ "server_time=带时区的服务器时间。无入参。")
public Map<String, Object> getContext() {
AuthContext ctx = AuthContextHolder.get();
if (ctx == null) {
throw new IllegalStateException("鉴权上下文缺失");
}
return integrationContextService.buildContext(ctx);
}
}