Files
ai_academy/internal/agent/tools/mcp_call_guard.go
T
runny 7ec21f35b0 chore: 初始化仓库,导入项目基线代码
Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、
Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。
今日开发的培训推送管理改动随后单独提交。
2026-11-16 18:12:23 +08:00

40 lines
1.3 KiB
Go

package tools
import (
"context"
"encoding/json"
"academy/internal/types"
)
// MCPCallGuard can return a non-nil result to decline a new MCP invocation
// before it opens an approval or contacts the server. It grants no authority.
// Identity and arguments are the resolved native target, never proxy input.
type MCPCallGuard func(context.Context, string, string, json.RawMessage) (*types.ToolResult, error)
type mcpCallGuardKey struct{}
// SetMCPCallGuard applies only to this engine's registry, including MCP targets
// discovered later and direct tools rebuilt from refreshed service metadata.
func (r *ToolRegistry) SetMCPCallGuard(guard MCPCallGuard) { r.mcpCallGuard = guard }
func withMCPCallGuard(ctx context.Context, guard MCPCallGuard) context.Context {
if guard == nil {
return ctx
}
return context.WithValue(ctx, mcpCallGuardKey{}, guard)
}
func checkMCPCallGuard(ctx context.Context, service, tool string, args json.RawMessage) (*types.ToolResult, error) {
guard, _ := ctx.Value(mcpCallGuardKey{}).(MCPCallGuard)
if guard == nil {
return nil, nil
}
// An already-issued parent approval must finish its own consume/resume
// lifecycle. This fence prevents new duplicate calls and new prompt cards.
if exec, ok := ToolExecFromContext(ctx); ok && exec.Answered != nil {
return nil, nil
}
return guard(ctx, service, tool, args)
}