feat(mcp): add per-tool enable toggle (#2989)

* feat(mcp): add per-tool enable toggle

* style: format migration test

* fix(mcp): keep enable and approval updates from overwriting each other

Partial policy writes now touch only the supplied columns, and a missing
tenant fails closed so a disabled tool cannot slip through.

---------

Co-authored-by: myysophia <myysophia@users.noreply.github.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
main
ninesun 2026-09-05 17:19:20 +08:00 committed by GitHub
parent df7e84eb30
commit 1e36e071ec
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
23 changed files with 705 additions and 57 deletions

View File

@ -53,6 +53,7 @@ export interface MCPTool {
description: string
inputSchema: Record<string, any>
require_approval?: boolean
enabled?: boolean
}
export interface MCPToolApprovalRow {
@ -61,6 +62,7 @@ export interface MCPToolApprovalRow {
service_id: string
tool_name: string
require_approval: boolean
enabled: boolean
}
export interface MCPResource {
@ -146,6 +148,10 @@ export async function setMCPToolApproval(serviceId: string, toolName: string, re
})
}
export async function setMCPToolEnabled(serviceId: string, toolName: string, enabled: boolean): Promise<void> {
await put(`/api/v1/mcp-services/${serviceId}/tool-approvals/${encodeURIComponent(toolName)}`, { enabled })
}
// ----------------------------------------------------------------------------
// Credential subresource (issue #988 follow-up).
//

View File

@ -4155,7 +4155,10 @@ export default {
emptyDescription: 'This service did not provide tools or resources',
requireApproval: 'Require human approval',
requireApprovalTip: 'When enabled, the agent pauses before calling this tool until you approve — use for DB writes, deletes, etc.',
approvalSaveFailed: 'Failed to save approval setting'
approvalSaveFailed: 'Failed to save approval setting',
toolEnabled: 'Enable tool',
toolEnabledTip: 'When disabled, the agent will not see or call this tool',
toolEnabledSaveFailed: 'Failed to save tool setting'
}
},
error: {

View File

@ -2621,7 +2621,10 @@ export default {
emptyDescription: '이 서비스에서 제공하는 도구 또는 리소스가 없습니다',
requireApproval: '수동 승인 필요',
requireApprovalTip: '활성화 시 에이전트가 이 도구를 호출하기 전에 승인을 기다립니다.',
approvalSaveFailed: '승인 설정 저장 실패'
approvalSaveFailed: '승인 설정 저장 실패',
toolEnabled: '도구 활성화',
toolEnabledTip: '비활성화하면 에이전트가 이 도구를 보거나 호출하지 않습니다.',
toolEnabledSaveFailed: '도구 설정 저장 실패'
}
},
system: {

View File

@ -2621,7 +2621,10 @@ export default {
emptyDescription: 'Сервис не предоставил инструменты или ресурсы',
requireApproval: 'Требуется подтверждение',
requireApprovalTip: 'При включении агент ждёт подтверждения перед вызовом инструмента.',
approvalSaveFailed: 'Не удалось сохранить настройку'
approvalSaveFailed: 'Не удалось сохранить настройку',
toolEnabled: 'Включить инструмент',
toolEnabledTip: 'Если отключить, агент не увидит и не вызовет этот инструмент.',
toolEnabledSaveFailed: 'Не удалось сохранить настройку инструмента'
}
},
system: {

View File

@ -2623,7 +2623,10 @@ export default {
emptyDescription: '该服务未提供工具或资源',
requireApproval: '需人工审核',
requireApprovalTip: '开启后,Agent 调用该工具前会暂停并等待确认,适用于可能改库/删文件等高危操作',
approvalSaveFailed: '保存审核设置失败'
approvalSaveFailed: '保存审核设置失败',
toolEnabled: '启用工具',
toolEnabledTip: '关闭后,Agent 不会再看到或调用该工具',
toolEnabledSaveFailed: '保存工具开关失败'
}
},
system: {

View File

@ -29,6 +29,18 @@
<t-icon name="tools" class="mtr-item-icon" />
<span class="mtr-item-name">{{ tool.name }}</span>
<div class="mtr-item-actions" @click.stop>
<t-tooltip v-if="serviceId" :content="$t('mcp.testResult.toolEnabledTip')" placement="top">
<span class="mtr-approval">
<span class="mtr-approval-label">{{ $t('mcp.testResult.toolEnabled') }}</span>
<t-switch
:value="tool.enabled !== false"
:loading="toolLoading[tool.name]"
:disabled="isToolPolicyBusy(tool.name)"
size="small"
@change="(v: boolean) => onToolEnabledChange(tool.name, v)"
/>
</span>
</t-tooltip>
<t-tooltip v-if="serviceId" :content="$t('mcp.testResult.requireApprovalTip')" placement="top">
<span class="mtr-approval">
<t-icon name="error-circle-filled" class="mtr-approval-icon" />
@ -36,6 +48,7 @@
<t-switch
:value="tool.require_approval"
:loading="approvalLoading[tool.name]"
:disabled="isToolPolicyBusy(tool.name)"
size="small"
@change="(v: boolean) => onRequireApprovalChange(tool.name, v)"
/>
@ -99,7 +112,7 @@
<script setup lang="ts">
import { ref, watch } from 'vue'
import type { MCPTestResult, MCPTool } from '@/api/mcp-service'
import { getMCPToolApprovals, setMCPToolApproval } from '@/api/mcp-service'
import { getMCPToolApprovals, setMCPToolApproval, setMCPToolEnabled } from '@/api/mcp-service'
import { MessagePlugin } from 'tdesign-vue-next'
import { useI18n } from 'vue-i18n'
@ -118,6 +131,10 @@ const expandedToolIndex = ref<number | null>(null)
const { t } = useI18n()
const displayTools = ref<MCPTool[]>([])
const approvalLoading = ref<Record<string, boolean>>({})
const toolLoading = ref<Record<string, boolean>>({})
const isToolPolicyBusy = (toolName: string) =>
Boolean(toolLoading.value[toolName] || approvalLoading.value[toolName])
const mergeApprovals = async () => {
const tools = props.result?.tools
@ -131,16 +148,33 @@ const mergeApprovals = async () => {
}
try {
const rows = await getMCPToolApprovals(props.serviceId)
const map = new Map(rows.map((r) => [r.tool_name, r.require_approval]))
const map = new Map(rows.map((r) => [r.tool_name, r]))
displayTools.value = tools.map((tool) => ({
...tool,
require_approval: map.get(tool.name) || false,
require_approval: map.get(tool.name)?.require_approval || false,
enabled: map.get(tool.name)?.enabled !== false,
}))
} catch {
displayTools.value = tools.map((x) => ({ ...x }))
}
}
const onToolEnabledChange = async (toolName: string, value: boolean) => {
if (!props.serviceId) return
toolLoading.value = { ...toolLoading.value, [toolName]: true }
try {
await setMCPToolEnabled(props.serviceId, toolName, value)
displayTools.value = displayTools.value.map((x) =>
x.name === toolName ? { ...x, enabled: value } : x
)
} catch (e) {
console.error(e)
MessagePlugin.error(t('mcp.testResult.toolEnabledSaveFailed'))
} finally {
toolLoading.value = { ...toolLoading.value, [toolName]: false }
}
}
watch(
() => [props.active, props.serviceId, props.result?.tools],
() => {

View File

@ -67,9 +67,10 @@ func pubsubChannel() string {
return pubsubChannelBase
}
// Checker answers whether a concrete MCP tool requires human approval before execution.
// Checker answers per-tool MCP policy questions used during registration and execution.
type Checker interface {
IsRequired(ctx context.Context, tenantID uint64, serviceID, toolName string) (bool, error)
IsEnabled(ctx context.Context, tenantID uint64, serviceID, toolName string) (bool, error)
}
// Decision is the outcome of a pending tool approval.
@ -101,6 +102,7 @@ type PendingRequest struct {
// MCPApproval is the surface used by MCPTool (mockable in tests).
type MCPApproval interface {
NeedsApproval(ctx context.Context, tenantID uint64, serviceID, toolName string) bool
IsEnabled(ctx context.Context, tenantID uint64, serviceID, toolName string) (bool, error)
RequestAndWait(ctx context.Context, req PendingRequest) (Decision, error)
}
@ -305,6 +307,20 @@ func (g *Gate) NeedsApproval(ctx context.Context, tenantID uint64, serviceID, to
return ok
}
// IsEnabled reports whether a per-tool MCP policy allows registration or
// execution. An absent gate/checker keeps tools enabled (policy store is
// optional). A missing tenant or tool identity is fail-closed: the caller
// cannot attribute a tenant-scoped disable flag, so the tool is not allowed.
func (g *Gate) IsEnabled(ctx context.Context, tenantID uint64, serviceID, toolName string) (bool, error) {
if g == nil || g.checker == nil {
return true, nil
}
if tenantID == 0 || serviceID == "" || toolName == "" {
return false, nil
}
return g.checker.IsEnabled(ctx, tenantID, serviceID, toolName)
}
// RequestAndWait emits a UI event, then blocks until Resolve, timeout, or ctx cancellation.
func (g *Gate) RequestAndWait(ctx context.Context, req PendingRequest) (Decision, error) {
if g == nil {
@ -670,9 +686,12 @@ func (g *Gate) deliverLocal(tenantID uint64, userID, pendingID string, d Decisio
type Adapter struct {
Svc interface {
IsRequired(ctx context.Context, tenantID uint64, serviceID, toolName string) (bool, error)
IsEnabled(ctx context.Context, tenantID uint64, serviceID, toolName string) (bool, error)
}
}
var _ Checker = (*Adapter)(nil)
// IsRequired implements Checker.
func (a *Adapter) IsRequired(ctx context.Context, tenantID uint64, serviceID, toolName string) (bool, error) {
if a == nil || a.Svc == nil {
@ -680,3 +699,11 @@ func (a *Adapter) IsRequired(ctx context.Context, tenantID uint64, serviceID, to
}
return a.Svc.IsRequired(ctx, tenantID, serviceID, toolName)
}
// IsEnabled implements Checker.
func (a *Adapter) IsEnabled(ctx context.Context, tenantID uint64, serviceID, toolName string) (bool, error) {
if a == nil || a.Svc == nil {
return true, nil
}
return a.Svc.IsEnabled(ctx, tenantID, serviceID, toolName)
}

View File

@ -12,14 +12,26 @@ import (
)
type stubChecker struct {
required bool
err error
required bool
err error
enabled *bool
enabledErr error
}
func (s *stubChecker) IsRequired(ctx context.Context, tenantID uint64, serviceID, toolName string) (bool, error) {
return s.required, s.err
}
func (s *stubChecker) IsEnabled(ctx context.Context, tenantID uint64, serviceID, toolName string) (bool, error) {
if s.enabledErr != nil {
return false, s.enabledErr
}
if s.enabled == nil {
return true, nil
}
return *s.enabled, nil
}
func TestGate_RequestAndWait_Approve(t *testing.T) {
bus := event.NewEventBus()
g := NewGate(&config.Config{Agent: &config.AgentConfig{ToolApprovalTimeoutSeconds: 2}}, &stubChecker{required: true}, nil)
@ -220,3 +232,45 @@ func TestGate_Resolve_RaceWinsAlreadyResolved(t *testing.T) {
"unexpected error: %v", r.second,
)
}
func boolPtr(v bool) *bool { return &v }
func TestGate_IsEnabled_NoCheckerKeepsToolsOn(t *testing.T) {
g := NewGate(nil, nil, nil)
enabled, err := g.IsEnabled(context.Background(), 1, "svc", "tool")
require.NoError(t, err)
require.True(t, enabled)
}
func TestGate_IsEnabled_MissingTenantFailClosed(t *testing.T) {
g := NewGate(nil, &stubChecker{}, nil)
enabled, err := g.IsEnabled(context.Background(), 0, "svc", "tool")
require.NoError(t, err)
require.False(t, enabled)
}
func TestGate_IsEnabled_HonorsChecker(t *testing.T) {
g := NewGate(nil, &stubChecker{enabled: boolPtr(false)}, nil)
enabled, err := g.IsEnabled(context.Background(), 1, "svc", "tool")
require.NoError(t, err)
require.False(t, enabled)
}
func TestGate_IsEnabled_CheckerErrorPropagates(t *testing.T) {
g := NewGate(nil, &stubChecker{enabledErr: context.DeadlineExceeded}, nil)
enabled, err := g.IsEnabled(context.Background(), 1, "svc", "tool")
require.Error(t, err)
require.False(t, enabled)
}
func TestAdapter_IsEnabled(t *testing.T) {
a := &Adapter{Svc: &stubChecker{enabled: boolPtr(false)}}
enabled, err := a.IsEnabled(context.Background(), 1, "svc", "tool")
require.NoError(t, err)
require.False(t, enabled)
empty := &Adapter{}
enabled, err = empty.IsEnabled(context.Background(), 1, "svc", "tool")
require.NoError(t, err)
require.True(t, enabled)
}

View File

@ -103,6 +103,20 @@ func (t *MCPTool) Parameters() json.RawMessage {
func (t *MCPTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
logger.GetLogger(ctx).Infof("Executing MCP tool: %s from service: %s", t.mcpTool.Name, t.service.Name)
// Re-check the policy at call time as well as during registration. An agent
// engine may outlive a settings change, and a disabled tool must not remain
// callable merely because it was registered before the toggle was changed.
if t.gate != nil {
tenantID, ok := mcpPolicyTenantID(ctx)
if !ok {
return disabledMCPToolResult(nil), nil
}
enabled, policyErr := t.gate.IsEnabled(ctx, tenantID, t.service.ID, t.mcpTool.Name)
if policyErr != nil || !enabled {
return disabledMCPToolResult(policyErr), nil
}
}
// Parse args from json.RawMessage
var input MCPInput
if err := json.Unmarshal(args, &input); err != nil {
@ -387,6 +401,19 @@ func extractContentText(content []mcp.ContentItem) string {
return strings.Join(textParts, "\n")
}
func mcpPolicyTenantID(ctx context.Context) (uint64, bool) {
tenantID, ok := types.TenantIDFromContext(ctx)
return tenantID, ok && tenantID != 0
}
func disabledMCPToolResult(policyErr error) *types.ToolResult {
message := "MCP tool is disabled"
if policyErr != nil {
message = fmt.Sprintf("MCP tool policy check failed: %v", policyErr)
}
return &types.ToolResult{Success: false, Error: message}
}
// sanitizeName sanitizes a name to create a valid identifier
func sanitizeName(name string) string {
// Replace invalid characters with underscores
@ -492,6 +519,25 @@ func RegisterMCPTools(
// Register each tool
for _, mcpTool := range mcpTools {
if gate != nil {
policyTenantID, ok := mcpPolicyTenantID(ctx)
if !ok {
logger.GetLogger(ctx).Warnf(
"Skipping MCP tool %s/%s: tenant id missing from context",
service.Name, mcpTool.Name,
)
continue
}
enabled, policyErr := gate.IsEnabled(ctx, policyTenantID, service.ID, mcpTool.Name)
if policyErr != nil {
logger.GetLogger(ctx).Warnf("Failed to read enabled policy for MCP tool %s/%s: %v", service.Name, mcpTool.Name, policyErr)
continue
}
if !enabled {
logger.GetLogger(ctx).Infof("MCP tool disabled by policy: %s from service: %s", mcpTool.Name, service.Name)
continue
}
}
tool := NewMCPTool(service, mcpTool, mcpManager, gate, authWaitTimeoutSeconds)
toolName := tool.Name()

View File

@ -0,0 +1,69 @@
package tools
import (
"context"
"encoding/json"
"errors"
"testing"
"github.com/Tencent/WeKnora/internal/agent/approval"
"github.com/Tencent/WeKnora/internal/types"
"github.com/stretchr/testify/require"
)
type staticPolicyGate struct {
enabled bool
err error
}
func (g staticPolicyGate) NeedsApproval(context.Context, uint64, string, string) bool {
return false
}
func (g staticPolicyGate) IsEnabled(context.Context, uint64, string, string) (bool, error) {
return g.enabled, g.err
}
func (g staticPolicyGate) RequestAndWait(context.Context, approval.PendingRequest) (approval.Decision, error) {
return approval.Decision{Approved: true}, nil
}
var _ approval.MCPApproval = staticPolicyGate{}
func TestMCPToolExecuteDisabledByPolicy(t *testing.T) {
tool := &MCPTool{
service: &types.MCPService{ID: "svc-1", Name: "weather"},
mcpTool: &types.MCPTool{Name: "get_forecast"},
gate: staticPolicyGate{enabled: false},
}
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7))
result, err := tool.Execute(ctx, json.RawMessage(`{}`))
require.NoError(t, err)
require.False(t, result.Success)
require.Equal(t, "MCP tool is disabled", result.Error)
}
func TestMCPToolExecutePolicyError(t *testing.T) {
tool := &MCPTool{
service: &types.MCPService{ID: "svc-1", Name: "weather"},
mcpTool: &types.MCPTool{Name: "get_forecast"},
gate: staticPolicyGate{err: errors.New("db down")},
}
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7))
result, err := tool.Execute(ctx, json.RawMessage(`{}`))
require.NoError(t, err)
require.False(t, result.Success)
require.Contains(t, result.Error, "db down")
}
func TestMCPToolExecuteMissingTenantFailClosed(t *testing.T) {
tool := &MCPTool{
service: &types.MCPService{ID: "svc-1", Name: "weather"},
mcpTool: &types.MCPTool{Name: "get_forecast"},
gate: staticPolicyGate{enabled: true},
}
result, err := tool.Execute(context.Background(), json.RawMessage(`{}`))
require.NoError(t, err)
require.False(t, result.Success)
require.Equal(t, "MCP tool is disabled", result.Error)
}

View File

@ -52,35 +52,77 @@ func (r *MCPToolApprovalRepository) IsRequired(ctx context.Context, tenantID uin
return row.RequireApproval, nil
}
// Upsert creates or updates the approval flag for a tool atomically.
// Uses ON CONFLICT against the (tenant_id, service_id, tool_name) unique index
// so concurrent writers don't race the prior SELECT-then-INSERT path into
// duplicate-key 500s.
func (r *MCPToolApprovalRepository) Upsert(ctx context.Context, row *types.MCPToolApproval) error {
if row == nil {
return errors.New("row is nil")
// IsEnabled returns true when a tool has no stored policy row. This preserves
// the historical behaviour for tools discovered before per-tool settings.
func (r *MCPToolApprovalRepository) IsEnabled(ctx context.Context, tenantID uint64, serviceID, toolName string) (bool, error) {
var row types.MCPToolApproval
err := r.db.WithContext(ctx).
Select("enabled").
Where("tenant_id = ? AND service_id = ? AND tool_name = ?", tenantID, serviceID, toolName).
First(&row).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return true, nil
}
if row.ID == "" {
row.ID = uuid.New().String()
if err != nil {
return false, fmt.Errorf("get mcp tool enabled state: %w", err)
}
return row.Enabled, nil
}
// UpsertPolicy creates or updates only the supplied policy columns.
// Concurrent patches of different fields cannot clobber each other because
// ON CONFLICT updates omit unchanged columns. A first insert uses
// require_approval=false and enabled=true for any field the patch omits.
func (r *MCPToolApprovalRepository) UpsertPolicy(
ctx context.Context, tenantID uint64, serviceID, toolName string, patch types.MCPToolPolicyPatch,
) error {
if serviceID == "" || toolName == "" {
return errors.New("service_id and tool_name are required")
}
if patch.RequireApproval == nil && patch.Enabled == nil {
return errors.New("require_approval or enabled is required")
}
now := time.Now()
row.UpdatedAt = now
if row.CreatedAt.IsZero() {
row.CreatedAt = now
requireApproval := false
if patch.RequireApproval != nil {
requireApproval = *patch.RequireApproval
}
err := r.db.WithContext(ctx).Clauses(clause.OnConflict{
enabled := true
if patch.Enabled != nil {
enabled = *patch.Enabled
}
updates := map[string]interface{}{"updated_at": now}
if patch.RequireApproval != nil {
updates["require_approval"] = *patch.RequireApproval
}
if patch.Enabled != nil {
updates["enabled"] = *patch.Enabled
}
row := map[string]interface{}{
"id": uuid.New().String(),
"tenant_id": tenantID,
"service_id": serviceID,
"tool_name": toolName,
"require_approval": requireApproval,
"enabled": enabled,
"created_at": now,
"updated_at": now,
}
// Create via map so enabled=false is persisted. GORM struct inserts omit
// bool zero values when the field has a default tag.
err := r.db.WithContext(ctx).Model(&types.MCPToolApproval{}).Clauses(clause.OnConflict{
Columns: []clause.Column{
{Name: "tenant_id"},
{Name: "service_id"},
{Name: "tool_name"},
},
DoUpdates: clause.Assignments(map[string]interface{}{
"require_approval": row.RequireApproval,
"updated_at": now,
}),
DoUpdates: clause.Assignments(updates),
}).Create(row).Error
if err != nil {
return fmt.Errorf("upsert mcp tool approval: %w", err)
return fmt.Errorf("upsert mcp tool policy: %w", err)
}
return nil
}

View File

@ -0,0 +1,122 @@
package repository
import (
"context"
"fmt"
"sync"
"testing"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/stretchr/testify/require"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
func newMCPToolApprovalTestRepo(t *testing.T) interfaces.MCPToolApprovalRepository {
t.Helper()
dsn := fmt.Sprintf("file:%s?mode=memory&cache=shared&_busy_timeout=5000", t.Name())
db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{})
require.NoError(t, err)
require.NoError(t, db.AutoMigrate(&types.MCPToolApproval{}))
return NewMCPToolApprovalRepository(db)
}
func boolPtr(v bool) *bool { return &v }
func TestMCPToolApprovalIsEnabledDefaultsTrue(t *testing.T) {
repo := newMCPToolApprovalTestRepo(t)
ctx := context.Background()
enabled, err := repo.IsEnabled(ctx, 1, "svc", "tool")
require.NoError(t, err)
require.True(t, enabled)
required, err := repo.IsRequired(ctx, 1, "svc", "tool")
require.NoError(t, err)
require.False(t, required)
}
func TestMCPToolApprovalUpsertPolicyInsertDefaults(t *testing.T) {
repo := newMCPToolApprovalTestRepo(t)
ctx := context.Background()
require.NoError(t, repo.UpsertPolicy(ctx, 1, "svc", "only-require", types.MCPToolPolicyPatch{
RequireApproval: boolPtr(true),
}))
enabled, err := repo.IsEnabled(ctx, 1, "svc", "only-require")
require.NoError(t, err)
require.True(t, enabled, "new rows must stay enabled when only approval is set")
required, err := repo.IsRequired(ctx, 1, "svc", "only-require")
require.NoError(t, err)
require.True(t, required)
require.NoError(t, repo.UpsertPolicy(ctx, 1, "svc", "only-enabled", types.MCPToolPolicyPatch{
Enabled: boolPtr(false),
}))
enabled, err = repo.IsEnabled(ctx, 1, "svc", "only-enabled")
require.NoError(t, err)
require.False(t, enabled)
required, err = repo.IsRequired(ctx, 1, "svc", "only-enabled")
require.NoError(t, err)
require.False(t, required, "new rows must keep require_approval=false when only enabled is set")
}
func TestMCPToolApprovalUpsertPolicyPreservesOtherColumn(t *testing.T) {
repo := newMCPToolApprovalTestRepo(t)
ctx := context.Background()
require.NoError(t, repo.UpsertPolicy(ctx, 1, "svc", "tool", types.MCPToolPolicyPatch{
Enabled: boolPtr(false),
}))
require.NoError(t, repo.UpsertPolicy(ctx, 1, "svc", "tool", types.MCPToolPolicyPatch{
RequireApproval: boolPtr(true),
}))
enabled, err := repo.IsEnabled(ctx, 1, "svc", "tool")
require.NoError(t, err)
require.False(t, enabled, "approval patch must not re-enable a disabled tool")
required, err := repo.IsRequired(ctx, 1, "svc", "tool")
require.NoError(t, err)
require.True(t, required)
require.NoError(t, repo.UpsertPolicy(ctx, 1, "svc", "tool", types.MCPToolPolicyPatch{
Enabled: boolPtr(true),
}))
required, err = repo.IsRequired(ctx, 1, "svc", "tool")
require.NoError(t, err)
require.True(t, required, "enabled patch must not clear require_approval")
}
func TestMCPToolApprovalConcurrentColumnPatches(t *testing.T) {
repo := newMCPToolApprovalTestRepo(t)
ctx := context.Background()
require.NoError(t, repo.UpsertPolicy(ctx, 1, "svc", "tool", types.MCPToolPolicyPatch{
RequireApproval: boolPtr(false),
Enabled: boolPtr(true),
}))
var wg sync.WaitGroup
errs := make(chan error, 2)
wg.Add(2)
go func() {
defer wg.Done()
errs <- repo.UpsertPolicy(ctx, 1, "svc", "tool", types.MCPToolPolicyPatch{Enabled: boolPtr(false)})
}()
go func() {
defer wg.Done()
errs <- repo.UpsertPolicy(ctx, 1, "svc", "tool", types.MCPToolPolicyPatch{RequireApproval: boolPtr(true)})
}()
wg.Wait()
close(errs)
for err := range errs {
require.NoError(t, err)
}
enabled, err := repo.IsEnabled(ctx, 1, "svc", "tool")
require.NoError(t, err)
require.False(t, enabled)
required, err := repo.IsRequired(ctx, 1, "svc", "tool")
require.NoError(t, err)
require.True(t, required)
}

View File

@ -32,12 +32,15 @@ func (s *mcpToolApprovalService) ListByService(ctx context.Context, tenantID uin
return s.repo.ListByService(ctx, tenantID, serviceID)
}
func (s *mcpToolApprovalService) SetRequireApproval(
ctx context.Context, tenantID uint64, serviceID, toolName string, require bool,
func (s *mcpToolApprovalService) SetPolicy(
ctx context.Context, tenantID uint64, serviceID, toolName string, requireApproval, enabled *bool,
) error {
if toolName == "" {
return fmt.Errorf("tool_name is required")
}
if requireApproval == nil && enabled == nil {
return fmt.Errorf("require_approval or enabled is required")
}
svc, err := s.mcpRepo.GetByID(ctx, tenantID, serviceID)
if err != nil {
return err
@ -45,15 +48,28 @@ func (s *mcpToolApprovalService) SetRequireApproval(
if svc == nil {
return fmt.Errorf("mcp service not found")
}
row := &types.MCPToolApproval{
TenantID: tenantID,
ServiceID: serviceID,
ToolName: toolName,
RequireApproval: require,
}
return s.repo.Upsert(ctx, row)
return s.repo.UpsertPolicy(ctx, tenantID, serviceID, toolName, types.MCPToolPolicyPatch{
RequireApproval: requireApproval,
Enabled: enabled,
})
}
func (s *mcpToolApprovalService) SetRequireApproval(
ctx context.Context, tenantID uint64, serviceID, toolName string, require bool,
) error {
return s.SetPolicy(ctx, tenantID, serviceID, toolName, &require, nil)
}
func (s *mcpToolApprovalService) SetEnabled(
ctx context.Context, tenantID uint64, serviceID, toolName string, enabled bool,
) error {
return s.SetPolicy(ctx, tenantID, serviceID, toolName, nil, &enabled)
}
func (s *mcpToolApprovalService) IsRequired(ctx context.Context, tenantID uint64, serviceID, toolName string) (bool, error) {
return s.repo.IsRequired(ctx, tenantID, serviceID, toolName)
}
func (s *mcpToolApprovalService) IsEnabled(ctx context.Context, tenantID uint64, serviceID, toolName string) (bool, error) {
return s.repo.IsEnabled(ctx, tenantID, serviceID, toolName)
}

View File

@ -0,0 +1,81 @@
package service
import (
"context"
"testing"
"github.com/Tencent/WeKnora/internal/application/repository"
"github.com/Tencent/WeKnora/internal/types"
"github.com/stretchr/testify/require"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
func newMCPToolApprovalServiceForTest(t *testing.T) (*mcpToolApprovalService, *fakeMCPRepo) {
t.Helper()
db, err := gorm.Open(sqlite.Open("file:"+t.Name()+"?mode=memory&cache=shared"), &gorm.Config{})
require.NoError(t, err)
require.NoError(t, db.AutoMigrate(&types.MCPToolApproval{}))
mcpRepo := newFakeMCPRepo()
require.NoError(t, mcpRepo.Create(context.Background(), &types.MCPService{
ID: "svc-1", TenantID: 1, Name: "weather",
}))
svc := NewMCPToolApprovalService(repository.NewMCPToolApprovalRepository(db), mcpRepo)
return svc.(*mcpToolApprovalService), mcpRepo
}
func TestMCPToolApprovalServiceSetEnabledPreservesApproval(t *testing.T) {
svc, _ := newMCPToolApprovalServiceForTest(t)
ctx := context.Background()
require.NoError(t, svc.SetRequireApproval(ctx, 1, "svc-1", "get_forecast", true))
require.NoError(t, svc.SetEnabled(ctx, 1, "svc-1", "get_forecast", false))
required, err := svc.IsRequired(ctx, 1, "svc-1", "get_forecast")
require.NoError(t, err)
require.True(t, required)
enabled, err := svc.IsEnabled(ctx, 1, "svc-1", "get_forecast")
require.NoError(t, err)
require.False(t, enabled)
}
func TestMCPToolApprovalServiceSetRequireApprovalPreservesDisabled(t *testing.T) {
svc, _ := newMCPToolApprovalServiceForTest(t)
ctx := context.Background()
require.NoError(t, svc.SetEnabled(ctx, 1, "svc-1", "get_forecast", false))
require.NoError(t, svc.SetRequireApproval(ctx, 1, "svc-1", "get_forecast", true))
enabled, err := svc.IsEnabled(ctx, 1, "svc-1", "get_forecast")
require.NoError(t, err)
require.False(t, enabled)
required, err := svc.IsRequired(ctx, 1, "svc-1", "get_forecast")
require.NoError(t, err)
require.True(t, required)
}
func TestMCPToolApprovalServiceSetPolicyWritesBothFieldsOnce(t *testing.T) {
svc, _ := newMCPToolApprovalServiceForTest(t)
ctx := context.Background()
require.NoError(t, svc.SetPolicy(ctx, 1, "svc-1", "get_forecast", boolPtr(true), boolPtr(false)))
required, err := svc.IsRequired(ctx, 1, "svc-1", "get_forecast")
require.NoError(t, err)
require.True(t, required)
enabled, err := svc.IsEnabled(ctx, 1, "svc-1", "get_forecast")
require.NoError(t, err)
require.False(t, enabled)
}
func TestMCPToolApprovalServiceSetPolicyRejectsEmptyPatch(t *testing.T) {
svc, _ := newMCPToolApprovalServiceForTest(t)
err := svc.SetPolicy(context.Background(), 1, "svc-1", "get_forecast", nil, nil)
require.Error(t, err)
}
func TestMCPToolApprovalServiceUnknownService(t *testing.T) {
svc, _ := newMCPToolApprovalServiceForTest(t)
err := svc.SetEnabled(context.Background(), 1, "missing", "tool", false)
require.ErrorContains(t, err, "not found")
}

View File

@ -31,9 +31,10 @@ var versionedSQLiteColumns = map[string][]string{
"tenant_invitations": {"token", "accepted_count"}, // 000054
"embed_channels": {"allow_memory"}, // 000060
"mcp_oauth_tokens": {"principal_type", "principal_id"}, // 000064
"mcp_tool_approvals": {"enabled"}, // 000091
}
const expectedSQLiteMigrationVersion = 12
const expectedSQLiteMigrationVersion = 13
func TestSQLiteMigrationsCreateVersionedSchema(t *testing.T) {
repoRoot := sqliteRepoRoot(t)

View File

@ -519,7 +519,7 @@ func (h *MCPServiceHandler) GetMCPServiceResources(c *gin.Context) {
})
}
// ListMCPToolApprovals returns persisted require_approval flags for tools on an MCP service.
// ListMCPToolApprovals returns persisted per-tool policies for an MCP service.
func (h *MCPServiceHandler) ListMCPToolApprovals(c *gin.Context) {
ctx := c.Request.Context()
serviceID := secutils.SanitizeForLog(c.Param("id"))
@ -548,20 +548,22 @@ func (h *MCPServiceHandler) ListMCPToolApprovals(c *gin.Context) {
}
type setMCPToolApprovalBody struct {
RequireApproval bool `json:"require_approval"`
RequireApproval *bool `json:"require_approval"`
Enabled *bool `json:"enabled"`
}
// SetMCPToolApproval sets whether a tool requires human approval before the agent may call it.
// SetMCPToolApproval updates per-tool MCP policy fields. The route name is kept
// for backwards compatibility with the original approval-only endpoint.
//
// SetMCPToolApproval godoc
// @Summary 设置 MCP 工具人工审批策略
// @Description 为指定 MCP 服务下的某个工具设置/更新审批要求
// @Summary 设置 MCP 工具策略
// @Description 为指定 MCP 服务下的某个工具更新启用状态和/或人工审批要求。至少提供 require_approval 或 enabled 之一;省略的字段保持原值。
// @Tags MCP服务
// @Accept json
// @Produce json
// @Param id path string true "MCP 服务 ID"
// @Param tool_name path string true "工具名"
// @Param request body map[string]interface{} true "{require_approval: bool}"
// @Param request body map[string]interface{} true "{require_approval?: bool, enabled?: bool}"
// @Success 200 {object} map[string]interface{} "更新结果"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Failure 404 {object} errors.AppError "MCP 服务或工具不存在"
@ -588,7 +590,17 @@ func (h *MCPServiceHandler) SetMCPToolApproval(c *gin.Context) {
c.Error(errors.NewBadRequestError(err.Error()))
return
}
if err := h.mcpToolApprovalService.SetRequireApproval(ctx, tenantID, serviceID, toolName, body.RequireApproval); err != nil {
if body.RequireApproval == nil && body.Enabled == nil {
c.Error(errors.NewBadRequestError("require_approval or enabled is required"))
return
}
if err := h.mcpToolApprovalService.SetPolicy(
ctx, tenantID, serviceID, toolName, body.RequireApproval, body.Enabled,
); err != nil {
if strings.Contains(err.Error(), "not found") {
c.Error(errors.NewNotFoundError(err.Error()))
return
}
c.Error(errors.NewInternalServerError(err.Error()))
return
}

View File

@ -0,0 +1,100 @@
package handler
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/internal/middleware"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
type stubMCPToolApprovalService struct {
interfaces.MCPToolApprovalService
requireApproval *bool
enabled *bool
err error
}
func (s *stubMCPToolApprovalService) SetPolicy(
_ context.Context, _ uint64, _, _ string, requireApproval, enabled *bool,
) error {
s.requireApproval = requireApproval
s.enabled = enabled
return s.err
}
func newMCPToolApprovalRouter(svc interfaces.MCPToolApprovalService) *gin.Engine {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(middleware.ErrorHandler())
r.Use(func(c *gin.Context) {
c.Set(types.TenantIDContextKey.String(), uint64(7))
c.Next()
})
h := &MCPServiceHandler{mcpToolApprovalService: svc}
r.PUT("/mcp-services/:id/tool-approvals/:tool_name", h.SetMCPToolApproval)
return r
}
func TestSetMCPToolApprovalRejectsEmptyBody(t *testing.T) {
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPut, "/mcp-services/svc-1/tool-approvals/get_forecast", bytes.NewBufferString(`{}`))
req.Header.Set("Content-Type", "application/json")
newMCPToolApprovalRouter(&stubMCPToolApprovalService{}).ServeHTTP(w, req)
require.Equal(t, http.StatusBadRequest, w.Code)
}
func TestSetMCPToolApprovalPartialEnabled(t *testing.T) {
stub := &stubMCPToolApprovalService{}
w := httptest.NewRecorder()
req := httptest.NewRequest(
http.MethodPut,
"/mcp-services/svc-1/tool-approvals/get_forecast",
bytes.NewBufferString(`{"enabled":false}`),
)
req.Header.Set("Content-Type", "application/json")
newMCPToolApprovalRouter(stub).ServeHTTP(w, req)
require.Equal(t, http.StatusOK, w.Code)
require.Nil(t, stub.requireApproval)
require.NotNil(t, stub.enabled)
require.False(t, *stub.enabled)
}
func TestSetMCPToolApprovalPartialRequireApproval(t *testing.T) {
stub := &stubMCPToolApprovalService{}
w := httptest.NewRecorder()
req := httptest.NewRequest(
http.MethodPut,
"/mcp-services/svc-1/tool-approvals/get_forecast",
bytes.NewBufferString(`{"require_approval":true}`),
)
req.Header.Set("Content-Type", "application/json")
newMCPToolApprovalRouter(stub).ServeHTTP(w, req)
require.Equal(t, http.StatusOK, w.Code)
require.NotNil(t, stub.requireApproval)
require.True(t, *stub.requireApproval)
require.Nil(t, stub.enabled)
}
func TestSetMCPToolApprovalCombinedFields(t *testing.T) {
stub := &stubMCPToolApprovalService{}
body, err := json.Marshal(map[string]bool{"require_approval": true, "enabled": false})
require.NoError(t, err)
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPut, "/mcp-services/svc-1/tool-approvals/get_forecast", bytes.NewBuffer(body))
req.Header.Set("Content-Type", "application/json")
newMCPToolApprovalRouter(stub).ServeHTTP(w, req)
require.Equal(t, http.StatusOK, w.Code)
require.NotNil(t, stub.requireApproval)
require.True(t, *stub.requireApproval)
require.NotNil(t, stub.enabled)
require.False(t, *stub.enabled)
}

View File

@ -6,16 +6,20 @@ import (
"github.com/Tencent/WeKnora/internal/types"
)
// MCPToolApprovalRepository persists per-tool approval requirements.
// MCPToolApprovalRepository persists per-tool MCP policies.
type MCPToolApprovalRepository interface {
ListByService(ctx context.Context, tenantID uint64, serviceID string) ([]*types.MCPToolApproval, error)
IsRequired(ctx context.Context, tenantID uint64, serviceID, toolName string) (bool, error)
Upsert(ctx context.Context, row *types.MCPToolApproval) error
IsEnabled(ctx context.Context, tenantID uint64, serviceID, toolName string) (bool, error)
UpsertPolicy(ctx context.Context, tenantID uint64, serviceID, toolName string, patch types.MCPToolPolicyPatch) error
}
// MCPToolApprovalService is the business layer for MCP tool approval flags.
// MCPToolApprovalService is the business layer for MCP tool policies.
type MCPToolApprovalService interface {
ListByService(ctx context.Context, tenantID uint64, serviceID string) ([]*types.MCPToolApproval, error)
SetPolicy(ctx context.Context, tenantID uint64, serviceID, toolName string, requireApproval, enabled *bool) error
SetRequireApproval(ctx context.Context, tenantID uint64, serviceID, toolName string, require bool) error
SetEnabled(ctx context.Context, tenantID uint64, serviceID, toolName string, enabled bool) error
IsRequired(ctx context.Context, tenantID uint64, serviceID, toolName string) (bool, error)
IsEnabled(ctx context.Context, tenantID uint64, serviceID, toolName string) (bool, error)
}

View File

@ -123,16 +123,30 @@ type MCPTool struct {
RequireApproval bool `json:"require_approval,omitempty"`
}
// MCPToolApproval persists per-tool "danger / needs human approval" for an MCP service.
// Tool list itself comes from MCP ListTools; this table only stores overrides.
// MCPToolApproval persists per-tool policies for an MCP service, including
// whether the tool is enabled and whether calls require human approval.
// The tool list itself comes from MCP ListTools; this table stores overrides.
type MCPToolApproval struct {
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
TenantID uint64 `json:"tenant_id" gorm:"not null;uniqueIndex:idx_mcp_tool_approvals_tenant_svc_tool"`
ServiceID string `json:"service_id" gorm:"type:varchar(36);not null;uniqueIndex:idx_mcp_tool_approvals_tenant_svc_tool;index"`
ToolName string `json:"tool_name" gorm:"type:varchar(512);not null;uniqueIndex:idx_mcp_tool_approvals_tenant_svc_tool"`
RequireApproval bool `json:"require_approval" gorm:"not null;default:false"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
TenantID uint64 `json:"tenant_id" gorm:"not null;uniqueIndex:idx_mcp_tool_approvals_tenant_svc_tool"`
ServiceID string `json:"service_id" gorm:"type:varchar(36);not null;uniqueIndex:idx_mcp_tool_approvals_tenant_svc_tool;index"`
ToolName string `json:"tool_name" gorm:"type:varchar(512);not null;uniqueIndex:idx_mcp_tool_approvals_tenant_svc_tool"`
RequireApproval bool `json:"require_approval" gorm:"not null;default:false"`
// Enabled controls whether this tool is exposed to the Agent. Missing rows
// are treated as enabled for backwards compatibility. The DB/GORM default is
// true; inserts persist false via a map Create so GORM does not omit the
// Go zero value.
Enabled bool `json:"enabled" gorm:"not null;default:true"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// MCPToolPolicyPatch is a partial per-tool policy update. Nil fields are left
// unchanged on existing rows. A newly inserted row uses RequireApproval=false
// and Enabled=true for any omitted field.
type MCPToolPolicyPatch struct {
RequireApproval *bool
Enabled *bool
}
// BeforeCreate sets ID for MCPToolApproval.

View File

@ -0,0 +1 @@
ALTER TABLE mcp_tool_approvals DROP COLUMN enabled;

View File

@ -0,0 +1,2 @@
-- Per-tool MCP enable/disable policy. Missing rows are treated as enabled.
ALTER TABLE mcp_tool_approvals ADD COLUMN enabled BOOLEAN NOT NULL DEFAULT 1;

View File

@ -0,0 +1 @@
ALTER TABLE mcp_tool_approvals DROP COLUMN IF EXISTS enabled;

View File

@ -0,0 +1,4 @@
-- Per-tool MCP enable/disable policy. Existing rows and missing rows remain
-- enabled by default so this migration is backwards compatible.
ALTER TABLE mcp_tool_approvals
ADD COLUMN IF NOT EXISTS enabled BOOLEAN NOT NULL DEFAULT true;