mirror of
https://github.com/tiennm99/goclaw.git
synced 2026-10-04 12:13:15 +00:00
* fix(prompt): remove duplicate Team Members section from system prompt The TEAM.md context file already provides the Members section with better formatting. The system prompt section was redundant and inconsistently formatted. - Remove buildTeamMembersSection() call from system prompt building - Remove unused buildTeamMembersSection() function * fix(mcp): wire store to manager for prompt preview tool visibility MCP manager needs database access to query configured servers for tool visibility in prompt preview. - Add SetStore() method to MCP manager - Wire pgStores.MCP to manager after initialization - Add debug logging for MCP initialization flow * fix(systemprompt): hide Tooling section when agent has no tools The Tooling section header and boilerplate were displayed even when the agent had no tools available. Add early return in buildToolingSection() to skip the section entirely when toolNames is empty. This reduces prompt noise for agents with no tool access. * feat(mcp): cache tool descriptions for prompt preview visibility MCP tools now show descriptions in prompt preview without requiring a live server connection. - Add CacheToolDescriptions() method to MCPServerStore (PG + SQLite) - Cache tool descriptions in settings['tool_cache'] when server connects - Use cached descriptions in ListToolsForAgent (fallback: hints → cache → global) - Descriptions are auto-populated from live server manifest on connection - Admins can still override via tool_hints in server settings * test(mcp): add CacheToolDescriptions to MCPServerStore test fakes Commit 5ce410b6 added CacheToolDescriptions() to the MCPServerStore interface but missed updating test mock implementations, breaking go vet across internal/mcp, internal/agent, internal/http, and internal/channels/bitrix24. Add no-op implementations matching each fake's existing style. * fix(providers): enforce per-agent tool policy for Claude CLI provider The Claude CLI provider (stdio+MCP bridge) was not enforcing per-agent tool policy, unlike other providers where the policy-filtered tool list already drives the system prompt's Tooling section. Two gaps closed: 1. --disallowedTools was previously skipped entirely when no MCP config path was resolved, letting the CLI subprocess run with its full native toolset (Bash, Edit, Read, Write, Glob, Grep, WebFetch, WebSearch) regardless of agent policy. It's now unconditional and derived from the agent's actual allowed-tools list (state.Tool.AllowedTools), mapped to Claude CLI's native tool names. 2. The MCP bridge server executed any tool call without checking the calling agent's policy. It now resolves the agent's policy from context (via the existing HMAC-verified agent lookup) and denies calls to tools outside that agent's allowed set, logging security.mcp_bridge_denied on denial. Both gaps were closed using existing plumbing (PolicyEngine.WouldAllow, AgentData.ParseToolsConfig, the bridge context middleware) — no new cross-cutting mechanism was introduced. * feat(web): show MCP/tool schemas in system prompt preview dialog The prompt-preview API response includes a separate `tools` field (the actual JSON schemas sent to the LLM as the tools API parameter) alongside `prompt` (the system prompt text), but the web UI only rendered `prompt`, silently dropping the tools list. Add a collapsible Tools section to both the full-screen System Prompt dialog and the inline agent-detail preview, showing tool count, name, description, and expandable parameter schema per tool. i18n keys added to en/vi/zh locales. * fix(prompt): render pinned skills on bootstrap turns Pinned skills are documented (web UI copy) as "always inlined in the system prompt", but the entire Skills section was gated behind !cfg.IsBootstrap, so pinned skill XML never appeared on bootstrap turns (first message of a session) despite the promise. Separate pinned-skill rendering from bootstrap-suppressed guidance: - Bootstrap + pinned skills present: render pinned XML only, no search/manage guidance (which stays suppressed as before) - Non-bootstrap: unchanged behavior - Minimal/none modes: pinned skills always render regardless of bootstrap state Add regression tests covering all four prompt modes on bootstrap turns, plus a non-bootstrap guard confirming existing behavior is preserved. * fix(skills): resolve managed skills directory per-tenant, not master-only skills.Loader was wired at startup to scan a single fixed directory (the master tenant's managed-skills dir), making any skill belonging to a non-master tenant invisible to both pinned-skills prompt resolution and skill_search/use_skill, regardless of DB visibility settings. - Loader now resolves the calling tenant's managed-skills directory per-call via context (store.TenantIDFromContext), never enumerating other tenants' directories - Skill cache is now tenant-keyed to prevent slug collisions and cross-tenant cache leaks across tenants using the same skill slug - gateway_setup.go passes the root data dir instead of a pre-resolved master-tenant path Write-side tooling (skill_manage, publish_skill) was already correctly tenant-scoped per-operation — no changes needed there. Added TestLoader_ManagedSkills_TenantIsolation proving two tenants with same-slug/different-content skills never see each other's content, including after cache population from a different tenant's lookup. Known follow-up (not in this commit): skill_search's BM25 index is still a single process-global index shared across tenants, which is a related but separate cross-tenant search-result leak requiring its own scoped fix (per-tenant index maps + threading tenant context through ensureIndex/rebuildIndex). * fix(tools): scope skill_search BM25 index per-tenant SkillSearchTool held a single process-global BM25 index built once from whichever tenant's context first triggered ensureIndex, then reused for all subsequent Execute() calls regardless of caller — leaking one tenant's skill search results into another's, the search-path counterpart to the managed-directory bug fixed in 7b4668ad. - index/lastVersion are now keyed per-tenant (map[uuid.UUID]*tenantIndexState) - ensureIndex resolves the calling tenant from context and only builds/reads that tenant's index entry, never touching another tenant's cached state - Builtin/bundled skills remain visible in every tenant's index (Loader already merges those tiers correctly per 7b4668ad) Loader.Version() remains a single global counter — a version bump in one tenant causes unnecessary rebuilds in others but does not cause cross-tenant leakage, an acceptable tradeoff to avoid scope creep. Added TestSkillSearchTool_TenantIsolation proving two tenants with same-slug/different-content skills never see each other's search results, including after cache population from a different tenant. * fix(tools): fix group-spec expansion in tool policy engine PolicyEngine.registry was only ever set via SetRegistry(), which was never called in production (only in one test) — so pe.registry was permanently nil in production. Every group-expansion helper (applyProfile, intersectWithSpec, unionWithSpec, subtractSpec, expandSpec, matchDenySpec, filterByCapability) silently dropped any "group:*" spec entry instead of expanding it when registry was nil. Concretely: "group:mcp" (auto-injected into agentToolPolicy.AlsoAllow for any agent with MCP tools) never resolved to real tool names, so MCP tools connected successfully and appeared in prompt text (which reads the registry directly, bypassing PolicyEngine) but were never included in the actual ChatRequest.Tools payload sent to the LLM — confirmed live via mcp.agent.tools_loaded tools=6 immediately followed by mcp.filtered_tools mcp_defs_count=0 in the same request. This affects any agent relying on group-based grants, not just MCP. PolicyEngine is a shared/global singleton used concurrently across all agents (constructed once at gateway startup), so mutating a registry field per-call would be a data race. Fix instead threads the registry as an explicit parameter from FilterTools down through all internal group-expansion helpers, and adds IsDenied/WouldAllow registry parameters, removing the dead SetRegistry() mechanism entirely. Also fixes group expansion for the per-user-MCP-tools path: FilterTools is sometimes called with a userToolOverlay wrapping a *Registry rather than a *Registry directly; added Unwrap() to userToolOverlay so the new registry-resolution logic works for both cases. Added 4 tests proving group expansion works via the threaded parameter alone (no SetRegistry): plain registry allow, userToolOverlay allow, deny-side group expansion, and the WouldAllow bridge-server path. Blast radius note: this restores intended access for every agent configured with group:* specs (group:mcp, group:vault, group:goclaw, group:coding, etc.) that were silently inert before. Existing agent configs relying on group grants will gain the tool access they were nominally already configured for. * fix(mcp): cache tool descriptions from pool-connected servers too 5ce410b6 added tool-description caching (for prompt-preview visibility) only inside connectServer. connectViaPool — the separate connect path used when MCP connections go through the shared pool — never got the same caching hook, even though it shares the same underlying connectAndDiscover wire handshake. Confirmed live: cloudflare/docker connected via connectViaPool and received real descriptions over the wire, but prompt preview still showed blank descriptions because this path never wrote to the cache. Also removes the temporary mcp.connect.raw_tool debug log added earlier this session for diagnosing the same issue — no longer needed now that the root cause is fixed. * chore(skills): remove temporary pinned-skills diagnostic logging Confirmed live: pinned skills (caveman, infra-ansible-knowledge) now resolve correctly end-to-end for tenant-scoped agents. Debug logging added to trace the resolution chain is no longer needed. * fix(tools): deny always wins over AlsoAllow group grants AlsoAllow's unionWithSpec could reintroduce a tool explicitly listed in Deny, since it added tools back from allTools without re-checking deny specs. Previously masked because AlsoAllow's group-expansion was also broken (fixed in f7af95de this session) — group specs silently expanded to nothing, so this ordering bug never manifested. Now that group expansion works, an admin-denied tool that's also reachable via a group:* AlsoAllow entry (e.g. group:mcp) would silently reappear. Re-apply deny-spec subtraction as a final step after AlsoAllow union, for both global and per-agent policy, so deny always wins regardless of which allow mechanism tries to add a tool back. Added tests proving global and per-agent Deny correctly override an overlapping AlsoAllow group grant, while sibling non-denied tools in the same group remain allowed. * fix(mcp): enumerate cached tools instead of wildcard placeholder in prompt preview ListToolsForAgent (the prompt-preview path) collapsed any server with an empty ToolAllow (unrestricted grant — the common case) into a single "server__*" placeholder entry, even when tool_cache already had every real tool name and description from connect time (5ce410b6, 8ffd67b9). This meant agents with unrestricted MCP server access never saw individual tool names or descriptions in prompt preview, forcing trial-and-error tool usage. When ToolAllow is empty and tool_cache is populated, enumerate every cached tool (skipping any explicitly denied) and emit one MCPToolPreviewInfo per tool, matching the construction logic already used for the ToolAllow-non-empty case. Falls back to the single placeholder only when tool_cache is also empty (server never connected). The live (non-preview) conversation path, buildMCPToolDescs, does not have this bug — it resolves tool identity from the live connected registry, never from ToolAllow, so no placeholder shortcut exists there. Added tests covering both the cache-populated enumeration case and the no-cache placeholder fallback. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * fix(prompt): filter alias re-injection and add MCP schemas to preview ToolDefs Prompt-preview's tools: schema array (PreviewResult.ToolDefs) had two bugs, both preview-only — confirmed live conversations already use correctly-filtered tool payloads via buildToolsPayload/PolicyEngine.FilterTools, unaffected by either bug: 1. Alias re-injection iterated ALL registry aliases globally with no check against the deny-filtered toolNames list, letting denied tools reappear via their alias name (e.g. a denied canonical tool still showing up as its Claude-Code-compat alias like Bash/Edit/Write/Read). Now skips any alias whose canonical tool isn't in the filtered set. 2. MCP tool descriptions (from the store-based, connection-free ListToolsForAgent path) only ever fed the prompt TEXT section, never got converted into ToolDefinition schema objects — so the tools: array never showed MCP tools at all, even when the MCP section of the prompt text correctly listed them. Now appends a ToolDefinition per MCP tool with name+description populated and a placeholder {"type":"object"} Parameters schema, documented as preview-only (real parameter schemas require a live MCP connection, only available during an actual conversation turn). Added tests proving denied-tool-alias exclusion and MCP tool inclusion in preview ToolDefs. * feat(skills): inline full content for pinned skills instead of pointer-only Web UI documented "Pinned skills are always inlined in the system prompt", but BuildPinnedSummary was just BuildSummary with an allowlist filter — same as the general searchable skill list: name/description(truncated)/location pointer only, requiring use_skill+read_file round trips to get actual content. No code path inlined real SKILL.md content for pinned skills specifically. BuildPinnedSummary now reads and inlines full SKILL.md content (frontmatter stripped) per pinned skill inside <skill_instructions> tags. Per-skill (10000 bytes) and total (30000 bytes) size caps fall back to the original pointer-only format with a note when a skill is too large to inline, so oversized skills degrade gracefully instead of blowing the prompt budget. Added tests: full-content inlining, size-cap fallback, and tenant isolation for the new inline path (mirroring the existing managed- skills tenant isolation test). * fix(mcp): real parameter schemas and full policy enforcement in prompt preview Three interconnected fixes to prompt preview, none affecting the live conversation path (which was already correct): 1. Real MCP parameter schemas instead of a useless empty placeholder. tool_cache previously stored only name+description; extended to also capture the real JSON Schema from the MCP server's tools/list response (CachedToolInfo{Description, Parameters}) at connect time, for both direct-connect and pool-connect paths. Preview now shows complete, real input schemas instead of {"type":"object"} with no properties — verified against actual wire data from a live cloudflare MCP server showing genuinely rich schemas (zone_id, type, name, content, ttl, proxied, all typed with descriptions and correct required arrays) that were previously being discarded. Backward-compatible: old-shape cache entries degrade gracefully to description-only rather than crashing, self-healing on next connect. 2. Global tool deny now enforced in preview. BuildPreviewPrompt previously hand-rolled a partial policy reimplementation (per-agent deny only, explicitly skipping the full PolicyEngine "because runtime state isn't available in preview") — but PolicyEngine.WouldAllow already handles this per-tool-name without needing channel context. A tool denied via the global config (not per-agent) would appear in preview despite being correctly denied in every real conversation. Preview now calls WouldAllow per candidate tool, with a graceful per-agent-deny-only fallback when no PolicyEngine is wired (e.g. in tests). 3. MCP tools now also subject to the same policy check — previously the MCP tool supplement (store-based, connection-free tool listing) added MCP tool names unconditionally, bypassing WouldAllow entirely, so a denied MCP tool could still appear in preview. Added tests for all three: real-schema presence, global-deny exclusion for both core and MCP tools, and backward-compat cache handling. * fix(prompt): remove redundant per-tool MCP enumeration from prompt text Now that MCP tool schemas in the tools: API parameter are real and complete (1290d4f1), the ## MCP Tools prompt-text section's per-tool "- mcp_x__y: description" enumeration is pure duplication with zero added value — the model already gets each tool's real schema (including description) via tools:. buildMCPToolsInlineSection now keeps only the behavioral instructions that aren't expressible via JSON schema and thus aren't duplicated: prefer-MCP-over-core-tools guidance, and the optional-parameter guidance (don't guess/fill optional fields). The per-tool name+ description enumeration loop is removed. Section still only appears when the agent has MCP tools (len(cfg.MCPToolDescs) > 0, unchanged gate). Updated tests to assert the enumeration is gone while the behavioral instructions remain; ToolDefs assertions are now the authoritative check for MCP tool allow/deny filtering behavior (prompt text no longer enumerates names at all). * test(agent): update TeamContextInjection test for removed Team Members section TestBuildSystemPrompt_TeamContextInjection asserted the presence of a 'Team Members' prompt-text section that was intentionally removed in 71d33180 (duplicate of the canonical TEAM.md-context-file Members section, which has better formatting). The test was never updated to match, causing it to fail on every run since. Moved the assertion from wantIn to wantNotIn for the 3 affected subtests -- BuildSystemPrompt correctly no longer renders team-member roster info directly; that info now comes exclusively from the TEAM.md context-file mechanism, outside this test's isolated scope. * fix(prompt): resolve real registry for WouldAllow calls in preview BuildPreviewPrompt's two WouldAllow calls hardcoded reg=nil, silently breaking group:* expansion (e.g. group:mcp) needed to resolve the AlsoAllow grant production actually uses to grant MCP tool access (resolver_helpers.go's agentToolPolicyWithMCP injects AlsoAllow: ["group:mcp"]). With reg=nil, WouldAllow could match literal tool names fine (the 18 core/static tools) but could never resolve group-based grants, so every MCP tool silently failed WouldAllow and was excluded from preview -- confirmed live via curl: 18 tools returned, zero mcp_* ones, for an agent with genuinely working MCP access in real conversations. Live conversations were never affected -- internal/mcp/bridge_server.go's WouldAllow call already correctly passes a real registry. Fix resolves a real *tools.Registry from deps.ToolLister via tools.ResolveConcreteRegistry (the same helper used at the live call site), passing it to both WouldAllow calls instead of nil. Falls back to nil gracefully for test mocks that don't implement the full ToolExecutor interface, preserving existing test behavior. Added a test proving an MCP tool granted via the exact production AlsoAllow: ["group:mcp"] pattern is now correctly included in preview ToolDefs, where the old reg=nil bug would have silently excluded it. * fix(prompt): use literal deny check for MCP tools in preview, not group expansion The MCP-tools policy gate added in 1290d4f1 called WouldAllow with a real registry (per 9b5fd2eb), which requires group:mcp expansion against that registry to grant access via the production AlsoAllow: ["group:mcp"] pattern. But MCP tools are only ever registered into ephemeral per-agent registry clones at live connection time (manager_connect.go) -- never into the shared/global registry preview uses. group:mcp always resolved empty in preview's connection-free context, so WouldAllow denied every MCP tool -- confirmed live via tool-name diff: live conversations correctly included all 6 MCP tools, preview included zero. MCP access-granting is already correctly handled by ListToolsForAgent's own per-server tool_allow/tool_deny grant logic (confirmed working correctly earlier this session). The preview gate only needs to catch the narrower case of a literally-denied tool name via global/per-agent policy config -- it never needed group expansion. Replaced WouldAllow with IsDenied(nil, name, agentPolicy), which forces a pure literal-name match with zero registry dependency, matching the existing usage pattern already established elsewhere in policy.go. This class of bug cannot recur: there's no registry-passing code path left in this check to silently reintroduce group-expansion dependence. Added a test proving MCP tool inclusion in preview is independent of group-expansion outcome (no AlsoAllow: group:mcp needed for a non-denied tool to appear). Also reverts the temporary loop.filtered_tool_names/ preview_prompt.filtered_tool_names diagnostic logging used to capture the live-vs-preview tool-name comparison that diagnosed this bug. * fix(http): preserve real MCP parameter schemas through HTTP preview adapter mcpPreviewAdapter.ListToolsForAgent (the HTTP-layer glue converting mcp.MCPToolPreviewInfo to agent.MCPToolPreviewInfo for BuildPreviewPrompt) only copied RegisteredName and Description, silently dropping Parameters -- a bug present since this adapter was introduced (2499d0be/7e250244), unrelated to today's other MCP preview fixes. This was masked until d5fc6344 fixed MCP tools being excluded from preview entirely (a separate bug) -- once MCP tools started appearing again, this pre-existing adapter gap became visible: tools showed up correctly, but always with the bare {"type":"object"} placeholder instead of their real cached schema (confirmed live: update_dns_record missing its 7 real properties). One-line fix: copy Parameters through in the adapter's struct literal. Added a regression test constructing a real *mcp.Manager with populated tool_cache, asserting the adapter's output preserves specific real schema properties (not just non-nil Parameters) -- verified this test fails without the fix and passes with it. --------- Co-authored-by: Bruno Clermont <bruno.clermont@gmail.com> Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
579 lines
18 KiB
Go
579 lines
18 KiB
Go
package tools
|
|
|
|
import (
|
|
"log/slog"
|
|
"slices"
|
|
"strings"
|
|
"sync"
|
|
|
|
"github.com/nextlevelbuilder/goclaw/internal/config"
|
|
"github.com/nextlevelbuilder/goclaw/internal/providers"
|
|
)
|
|
|
|
// builtinToolGroups is const-like seed data for per-Registry tool groups.
|
|
// Do NOT modify at runtime — each Registry gets a deep copy in NewRegistry().
|
|
var builtinToolGroups = map[string][]string{
|
|
"memory": {"memory_search", "memory_get"},
|
|
"web": {"web_search", "web_fetch"},
|
|
"fs": {"read_file", "write_file", "list_files", "edit"},
|
|
"runtime": {"exec", "wait"},
|
|
"sessions": {"sessions_list", "sessions_history", "sessions_send", "spawn", "session_status"},
|
|
"ui": {"browser"},
|
|
"automation": {"cron"},
|
|
"messaging": {"message", "create_forum_topic", "list_group_members"},
|
|
"team": {"team_tasks"},
|
|
"vault": {"vault_search", "vault_read"},
|
|
// Composite group: all goclaw native tools (excludes MCP/custom plugins).
|
|
"goclaw": {
|
|
"read_file", "write_file", "list_files", "edit", "exec", "wait",
|
|
"web_search", "web_fetch", "browser",
|
|
"memory_search", "memory_get", "memory_expand",
|
|
"knowledge_graph_search", "vault_search", "vault_read",
|
|
"sessions_list", "sessions_history", "sessions_send", "spawn", "session_status",
|
|
"delegate",
|
|
"cron", "datetime", "heartbeat",
|
|
"message", "create_forum_topic", "list_group_members",
|
|
"read_image", "read_document", "read_audio", "read_video",
|
|
"create_image", "create_video", "create_audio",
|
|
"skill_search", "skill_manage", "publish_skill", "use_skill",
|
|
"mcp_tool_search", "tts",
|
|
"team_tasks",
|
|
},
|
|
}
|
|
|
|
// Package-level wrappers are REMOVED — use Registry methods instead.
|
|
// See Registry.RegisterToolGroup, Registry.MergeToolGroup, Registry.UnregisterToolGroup.
|
|
|
|
// Tool profiles define preset allow sets.
|
|
var toolProfiles = map[string][]string{
|
|
"minimal": {"session_status"},
|
|
"coding": {"group:fs", "group:runtime", "group:sessions", "group:memory", "group:web", "group:vault", "read_image", "create_image", "skill_search"},
|
|
"messaging": {"group:messaging", "wait", "group:web", "group:vault", "sessions_list", "sessions_history", "sessions_send", "session_status", "read_image", "skill_search"},
|
|
"full": {}, // empty = no restrictions
|
|
}
|
|
|
|
// Legacy tool aliases — migrated to Registry.RegisterAlias() at startup.
|
|
// resolveAlias() is used by IsDenied to expand names before deny-spec matching.
|
|
var legacyToolAliases = map[string]string{
|
|
"bash": "exec",
|
|
"apply-patch": "apply_patch",
|
|
"edit_file": "edit",
|
|
"sessions_spawn": "spawn",
|
|
}
|
|
|
|
// LegacyToolAliases returns legacy aliases for registration into the Registry.
|
|
func LegacyToolAliases() map[string]string {
|
|
return legacyToolAliases
|
|
}
|
|
|
|
// Subagent deny lists — tools subagents cannot use.
|
|
var subagentDenyList = []string{
|
|
"exec", // subagents should not shell out — main agent can still exec
|
|
"gateway", "agents_list", "whatsapp_login", "session_status",
|
|
"cron", "memory_search", "memory_get", "sessions_send",
|
|
}
|
|
|
|
// Leaf subagent deny — additional restrictions at max spawn depth.
|
|
var leafSubagentDenyList = []string{
|
|
"sessions_list", "sessions_history", "spawn",
|
|
}
|
|
|
|
// registryUnwrapper is implemented by ToolExecutor wrappers (e.g. userToolOverlay)
|
|
// that expose the concrete *Registry they wrap, so group-expansion machinery
|
|
// (which needs concrete *Registry, not the ToolExecutor interface) still works
|
|
// when the caller passes a request-scoped overlay instead of the raw registry.
|
|
type registryUnwrapper interface {
|
|
Unwrap() *Registry
|
|
}
|
|
|
|
// ResolveConcreteRegistry extracts the concrete *Registry backing a ToolExecutor,
|
|
// for use by group-expansion/capability/deny helpers that need direct access to
|
|
// registry-internal tool groups and metadata. Returns nil when the executor is
|
|
// neither a *Registry nor a registryUnwrapper (e.g. a test mock) — callers must
|
|
// tolerate nil (group expansion falls back to a no-op pass-through).
|
|
func ResolveConcreteRegistry(executor ToolExecutor) *Registry {
|
|
if reg, ok := executor.(*Registry); ok {
|
|
return reg
|
|
}
|
|
if unwrapper, ok := executor.(registryUnwrapper); ok {
|
|
return unwrapper.Unwrap()
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// PolicyEngine evaluates tool access based on layered config policies.
|
|
type PolicyEngine struct {
|
|
globalPolicy *config.ToolsConfig
|
|
mu sync.RWMutex // protects denyCapabilities
|
|
denyCapabilities []ToolCapability // capability-based deny rules (v3)
|
|
}
|
|
|
|
// NewPolicyEngine creates a policy engine from global config.
|
|
func NewPolicyEngine(cfg *config.ToolsConfig) *PolicyEngine {
|
|
return &PolicyEngine{globalPolicy: cfg}
|
|
}
|
|
|
|
// DenyCapability adds a capability to the deny list.
|
|
// Tools with this capability are excluded from FilterTools results.
|
|
func (pe *PolicyEngine) DenyCapability(cap ToolCapability) {
|
|
pe.mu.Lock()
|
|
defer pe.mu.Unlock()
|
|
pe.denyCapabilities = append(pe.denyCapabilities, cap)
|
|
}
|
|
|
|
// FilterTools returns only the tools allowed by the policy for the given context.
|
|
// It evaluates the 7-step pipeline and returns filtered provider definitions.
|
|
func (pe *PolicyEngine) FilterTools(
|
|
registry ToolExecutor,
|
|
agentID string,
|
|
providerName string,
|
|
agentToolPolicy *config.ToolPolicySpec,
|
|
groupToolAllow []string,
|
|
isSubagent bool,
|
|
isLeafAgent bool,
|
|
) []providers.ToolDefinition {
|
|
reg := ResolveConcreteRegistry(registry)
|
|
allTools := registry.List()
|
|
allowed := pe.evaluate(reg, allTools, providerName, agentToolPolicy, groupToolAllow)
|
|
|
|
// Step 8: Capability-based deny (v3 RBAC)
|
|
pe.mu.RLock()
|
|
denyCaps := pe.denyCapabilities
|
|
pe.mu.RUnlock()
|
|
if len(denyCaps) > 0 && reg != nil {
|
|
allowed = filterByCapability(allowed, denyCaps, reg)
|
|
}
|
|
|
|
// Apply subagent restrictions
|
|
if isSubagent {
|
|
allowed = subtractSet(allowed, subagentDenyList)
|
|
}
|
|
if isLeafAgent {
|
|
allowed = subtractSet(allowed, leafSubagentDenyList)
|
|
}
|
|
|
|
// Resolve aliases and build definitions
|
|
allowedSet := make(map[string]bool, len(allowed))
|
|
var defs []providers.ToolDefinition
|
|
for _, name := range allowed {
|
|
canonical := resolveAlias(name)
|
|
if tool, ok := registry.Get(canonical); ok {
|
|
defs = append(defs, ToProviderDef(tool))
|
|
allowedSet[canonical] = true
|
|
}
|
|
}
|
|
|
|
// Add registry aliases for allowed canonical tools.
|
|
// Sort alias names for deterministic ordering (prompt caching).
|
|
aliasMap := registry.Aliases()
|
|
aliasList := make([]string, 0, len(aliasMap))
|
|
for alias := range aliasMap {
|
|
aliasList = append(aliasList, alias)
|
|
}
|
|
slices.Sort(aliasList)
|
|
for _, alias := range aliasList {
|
|
canonical := aliasMap[alias]
|
|
if !allowedSet[canonical] {
|
|
continue
|
|
}
|
|
if tool, ok := registry.Get(canonical); ok {
|
|
defs = append(defs, providers.ToolDefinition{
|
|
Type: "function",
|
|
Function: &providers.ToolFunctionSchema{
|
|
Name: alias,
|
|
Description: tool.Description(),
|
|
Parameters: tool.Parameters(),
|
|
},
|
|
})
|
|
}
|
|
}
|
|
|
|
slog.Debug("tool policy applied",
|
|
"agent", agentID,
|
|
"provider", providerName,
|
|
"total_tools", len(allTools),
|
|
"allowed", len(defs),
|
|
"is_subagent", isSubagent,
|
|
)
|
|
|
|
return defs
|
|
}
|
|
|
|
// evaluate runs the 7-step policy pipeline.
|
|
// reg is the concrete *Registry backing the caller's ToolExecutor (may be nil
|
|
// when the caller passed a mock/test executor with no group data), used for
|
|
// group-expansion ("group:xxx") and deny-spec matching. It is threaded through
|
|
// as an explicit parameter — never stored on pe — because pe is a shared,
|
|
// concurrently-used singleton; mutating a field per-call would be a data race.
|
|
func (pe *PolicyEngine) evaluate(
|
|
reg *Registry,
|
|
allTools []string,
|
|
providerName string,
|
|
agentToolPolicy *config.ToolPolicySpec,
|
|
groupToolAllow []string,
|
|
) []string {
|
|
g := pe.globalPolicy
|
|
|
|
// Step 1: Global profile
|
|
allowed := pe.applyProfile(reg, allTools, g.Profile)
|
|
|
|
// Step 2: Provider-level profile override
|
|
if g.ByProvider != nil {
|
|
if pp, ok := g.ByProvider[providerName]; ok && pp.Profile != "" {
|
|
allowed = pe.applyProfile(reg, allTools, pp.Profile)
|
|
}
|
|
}
|
|
|
|
// Step 3: Global allow list (restricts to only these)
|
|
if len(g.Allow) > 0 {
|
|
allowed = intersectWithSpec(reg, allowed, g.Allow)
|
|
}
|
|
|
|
// Step 4: Provider-level allow override
|
|
if g.ByProvider != nil {
|
|
if pp, ok := g.ByProvider[providerName]; ok && len(pp.Allow) > 0 {
|
|
allowed = intersectWithSpec(reg, allowed, pp.Allow)
|
|
}
|
|
}
|
|
|
|
// Step 5: Per-agent allow
|
|
if agentToolPolicy != nil && len(agentToolPolicy.Allow) > 0 {
|
|
allowed = intersectWithSpec(reg, allowed, agentToolPolicy.Allow)
|
|
}
|
|
|
|
// Step 6: Per-agent per-provider allow
|
|
if agentToolPolicy != nil && agentToolPolicy.ByProvider != nil {
|
|
if pp, ok := agentToolPolicy.ByProvider[providerName]; ok && len(pp.Allow) > 0 {
|
|
allowed = intersectWithSpec(reg, allowed, pp.Allow)
|
|
}
|
|
}
|
|
|
|
// Step 7: Group-level allow
|
|
if len(groupToolAllow) > 0 {
|
|
allowed = intersectWithSpec(reg, allowed, groupToolAllow)
|
|
}
|
|
|
|
// Apply global deny
|
|
if len(g.Deny) > 0 {
|
|
allowed = subtractSpec(reg, allowed, g.Deny)
|
|
}
|
|
|
|
// Apply agent deny
|
|
if agentToolPolicy != nil && len(agentToolPolicy.Deny) > 0 {
|
|
allowed = subtractSpec(reg, allowed, agentToolPolicy.Deny)
|
|
}
|
|
|
|
// Apply alsoAllow (additive — adds back tools without removing existing)
|
|
if len(g.AlsoAllow) > 0 {
|
|
allowed = unionWithSpec(reg, allowed, allTools, g.AlsoAllow)
|
|
}
|
|
if agentToolPolicy != nil && len(agentToolPolicy.AlsoAllow) > 0 {
|
|
allowed = unionWithSpec(reg, allowed, allTools, agentToolPolicy.AlsoAllow)
|
|
}
|
|
|
|
// Deny always wins: re-apply the same deny specs as a final step so that
|
|
// AlsoAllow can never reintroduce a tool (or a group containing it) that
|
|
// was explicitly denied above. Without this, unionWithSpec adds tools back
|
|
// from allTools without re-checking the deny list.
|
|
if len(g.Deny) > 0 {
|
|
allowed = subtractSpec(reg, allowed, g.Deny)
|
|
}
|
|
if agentToolPolicy != nil && len(agentToolPolicy.Deny) > 0 {
|
|
allowed = subtractSpec(reg, allowed, agentToolPolicy.Deny)
|
|
}
|
|
|
|
return allowed
|
|
}
|
|
|
|
// applyProfile returns tools allowed by a named profile.
|
|
// "full" or empty profile = all tools allowed.
|
|
func (pe *PolicyEngine) applyProfile(reg *Registry, allTools []string, profile string) []string {
|
|
if profile == "" || profile == "full" {
|
|
return copySlice(allTools)
|
|
}
|
|
|
|
spec, ok := toolProfiles[profile]
|
|
if !ok {
|
|
slog.Warn("unknown tool profile, using full", "profile", profile)
|
|
return copySlice(allTools)
|
|
}
|
|
|
|
return expandSpec(reg, allTools, spec)
|
|
}
|
|
|
|
// --- Set operations with group expansion (using per-Registry tool groups) ---
|
|
|
|
// expandSpec expands a spec list (which may contain "group:xxx") into concrete tool names,
|
|
// filtered against available tools. Uses per-Registry tool groups to avoid cross-agent races.
|
|
func expandSpec(reg *Registry, available []string, spec []string) []string {
|
|
if reg == nil {
|
|
// Fallback: no group expansion
|
|
return expandSpecNoGroups(available, spec)
|
|
}
|
|
return reg.ExpandToolGroups(available, spec)
|
|
}
|
|
|
|
// expandSpecNoGroups is a fallback when no registry is available.
|
|
func expandSpecNoGroups(available []string, spec []string) []string {
|
|
expanded := make(map[string]bool)
|
|
for _, s := range spec {
|
|
if !strings.HasPrefix(s, "group:") {
|
|
expanded[s] = true
|
|
}
|
|
}
|
|
var result []string
|
|
for _, t := range available {
|
|
if expanded[t] {
|
|
result = append(result, t)
|
|
}
|
|
}
|
|
return result
|
|
}
|
|
|
|
// intersectWithSpec keeps only tools in `current` that match the spec (with group expansion).
|
|
func intersectWithSpec(reg *Registry, current []string, spec []string) []string {
|
|
if reg == nil {
|
|
return intersectWithSpecNoGroups(current, spec)
|
|
}
|
|
reg.toolGroupsMu.RLock()
|
|
defer reg.toolGroupsMu.RUnlock()
|
|
|
|
expanded := make(map[string]bool)
|
|
for _, s := range spec {
|
|
if after, ok := strings.CutPrefix(s, "group:"); ok {
|
|
if members, ok := reg.toolGroups[after]; ok {
|
|
for _, m := range members {
|
|
expanded[m] = true
|
|
}
|
|
}
|
|
} else {
|
|
expanded[s] = true
|
|
}
|
|
}
|
|
|
|
var result []string
|
|
for _, t := range current {
|
|
if expanded[t] {
|
|
result = append(result, t)
|
|
}
|
|
}
|
|
return result
|
|
}
|
|
|
|
func intersectWithSpecNoGroups(current []string, spec []string) []string {
|
|
expanded := make(map[string]bool)
|
|
for _, s := range spec {
|
|
if !strings.HasPrefix(s, "group:") {
|
|
expanded[s] = true
|
|
}
|
|
}
|
|
var result []string
|
|
for _, t := range current {
|
|
if expanded[t] {
|
|
result = append(result, t)
|
|
}
|
|
}
|
|
return result
|
|
}
|
|
|
|
// subtractSpec removes tools matching the spec (with group expansion) from current.
|
|
func subtractSpec(reg *Registry, current []string, spec []string) []string {
|
|
if reg == nil {
|
|
return subtractSpecNoGroups(current, spec)
|
|
}
|
|
reg.toolGroupsMu.RLock()
|
|
defer reg.toolGroupsMu.RUnlock()
|
|
|
|
denied := make(map[string]bool)
|
|
for _, s := range spec {
|
|
if after, ok := strings.CutPrefix(s, "group:"); ok {
|
|
if members, ok := reg.toolGroups[after]; ok {
|
|
for _, m := range members {
|
|
denied[m] = true
|
|
}
|
|
}
|
|
} else {
|
|
denied[s] = true
|
|
}
|
|
}
|
|
|
|
var result []string
|
|
for _, t := range current {
|
|
if !denied[t] {
|
|
result = append(result, t)
|
|
}
|
|
}
|
|
return result
|
|
}
|
|
|
|
func subtractSpecNoGroups(current []string, spec []string) []string {
|
|
denied := make(map[string]bool)
|
|
for _, s := range spec {
|
|
if !strings.HasPrefix(s, "group:") {
|
|
denied[s] = true
|
|
}
|
|
}
|
|
var result []string
|
|
for _, t := range current {
|
|
if !denied[t] {
|
|
result = append(result, t)
|
|
}
|
|
}
|
|
return result
|
|
}
|
|
|
|
// subtractSet removes exact tool names from current.
|
|
func subtractSet(current []string, deny []string) []string {
|
|
denied := make(map[string]bool, len(deny))
|
|
for _, d := range deny {
|
|
denied[d] = true
|
|
}
|
|
var result []string
|
|
for _, t := range current {
|
|
if !denied[t] {
|
|
result = append(result, t)
|
|
}
|
|
}
|
|
return result
|
|
}
|
|
|
|
// unionWithSpec adds tools matching spec (from allTools) to current set.
|
|
func unionWithSpec(reg *Registry, current []string, allTools []string, spec []string) []string {
|
|
existing := make(map[string]bool, len(current))
|
|
for _, t := range current {
|
|
existing[t] = true
|
|
}
|
|
|
|
toAdd := expandSpec(reg, allTools, spec)
|
|
for _, t := range toAdd {
|
|
if !existing[t] {
|
|
current = append(current, t)
|
|
existing[t] = true
|
|
}
|
|
}
|
|
return current
|
|
}
|
|
|
|
// WouldAllow checks whether a tool name would pass the full policy pipeline
|
|
// (profile → allow → deny → alsoAllow) if it were present in the registry.
|
|
// Used to filter per-user tools (e.g. per-user MCP tools) that intentionally
|
|
// bypass registration in the shared registry to prevent credential leaks, but
|
|
// still need to respect the agent's tool policy.
|
|
//
|
|
// reg is the concrete *Registry to use for group-expansion/deny-spec matching
|
|
// (pass nil to fall back to a no-group-expansion match, e.g. from a caller that
|
|
// only has a ToolExecutor). It works by running evaluate() with just [name] as
|
|
// the available set. With a "full" profile and no allow restrictions, the name
|
|
// survives. With a restrictive allow list that excludes MCP tools, it's
|
|
// removed. With a deny containing group:mcp, MatchDenySpec removes it from the set.
|
|
func (pe *PolicyEngine) WouldAllow(reg *Registry, name, providerName string, agentPolicy *config.ToolPolicySpec, groupAllow []string) bool {
|
|
allowed := pe.evaluate(reg, []string{name}, providerName, agentPolicy, groupAllow)
|
|
for _, a := range allowed {
|
|
if a == name {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// IsDenied checks if a tool name is explicitly denied by global or agent policy.
|
|
// Used to prevent lazy-activated deferred tools from bypassing the deny list.
|
|
// Checks under all candidate names: the raw name, the legacy alias (e.g. bash→exec),
|
|
// and the registry alias when available. reg is the concrete *Registry to use for
|
|
// group-expansion/deny-spec matching (nil is tolerated — falls back to a plain match).
|
|
func (pe *PolicyEngine) IsDenied(reg *Registry, name string, agentPolicy *config.ToolPolicySpec) bool {
|
|
candidates := map[string]struct{}{name: {}}
|
|
// Keep legacy alias compatibility (e.g. bash -> exec).
|
|
candidates[resolveAlias(name)] = struct{}{}
|
|
// Include registry alias mapping when available.
|
|
if reg != nil {
|
|
if canonical, ok := reg.Aliases()[name]; ok && canonical != "" {
|
|
candidates[canonical] = struct{}{}
|
|
}
|
|
}
|
|
|
|
if pe.globalPolicy != nil {
|
|
for candidate := range candidates {
|
|
if matchDenySpec(reg, candidate, pe.globalPolicy.Deny) {
|
|
return true
|
|
}
|
|
}
|
|
}
|
|
if agentPolicy != nil {
|
|
for candidate := range candidates {
|
|
if matchDenySpec(reg, candidate, agentPolicy.Deny) {
|
|
return true
|
|
}
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// matchDenySpec returns true if name matches any entry in the deny spec (with group expansion).
|
|
func matchDenySpec(reg *Registry, name string, spec []string) bool {
|
|
if reg == nil {
|
|
// No groups to expand — plain match only
|
|
return slices.Contains(spec, name)
|
|
}
|
|
return reg.MatchDenySpec(name, spec)
|
|
}
|
|
|
|
// StripToolPrefix removes a prefix pattern from a tool name returned by the LLM.
|
|
// The template uses {tool_name} as placeholder. Example: template "proxy_{tool_name}"
|
|
// strips "proxy_" from "proxy_exec" → "exec".
|
|
// If template has no {tool_name}, it's treated as a literal prefix to strip.
|
|
func StripToolPrefix(tmpl, name string) string {
|
|
const placeholder = "{tool_name}"
|
|
if strings.Contains(tmpl, placeholder) {
|
|
parts := strings.SplitN(tmpl, placeholder, 2)
|
|
prefix, suffix := parts[0], parts[1]
|
|
if strings.HasPrefix(name, prefix) && strings.HasSuffix(name, suffix) {
|
|
result := name[len(prefix):]
|
|
if suffix != "" {
|
|
result = result[:len(result)-len(suffix)]
|
|
}
|
|
if result != "" {
|
|
return result
|
|
}
|
|
}
|
|
return name
|
|
}
|
|
// Plain prefix: strip literal prefix and any leading underscore separator
|
|
stripped := strings.TrimPrefix(name, tmpl)
|
|
if stripped == name {
|
|
return name // prefix didn't match
|
|
}
|
|
stripped = strings.TrimPrefix(stripped, "_")
|
|
if stripped == "" {
|
|
return name // nothing left after stripping
|
|
}
|
|
slog.Debug("tool_prefix.stripped", "from", name, "to", stripped, "template", tmpl)
|
|
return stripped
|
|
}
|
|
|
|
func resolveAlias(name string) string {
|
|
if canonical, ok := legacyToolAliases[name]; ok {
|
|
return canonical
|
|
}
|
|
return name
|
|
}
|
|
|
|
func copySlice(s []string) []string {
|
|
c := make([]string, len(s))
|
|
copy(c, s)
|
|
return c
|
|
}
|
|
|
|
// filterByCapability removes tools whose metadata matches any denied capability.
|
|
func filterByCapability(names []string, denyCaps []ToolCapability, reg *Registry) []string {
|
|
out := make([]string, 0, len(names))
|
|
for _, name := range names {
|
|
meta := reg.GetMetadata(name)
|
|
denied := slices.ContainsFunc(denyCaps, meta.HasCapability)
|
|
if !denied {
|
|
out = append(out, name)
|
|
}
|
|
}
|
|
return out
|
|
}
|