fix(agent): harden @mention scope and simplify must_use hints
Tighten per-turn @MCP/@Skill/@tag handling after review: enforce agent MCP/Skill whitelist, ignore mentions when selection mode is none, tag-scope grep_chunks, and simplified English must_use lines without tool dumps. Skip persisting scope envelopes to history rendered_content.
This commit is contained in:
@@ -32,10 +32,11 @@ func (e *AgentEngine) streamFinalAnswerToEventBus(
|
||||
|
||||
// Build messages with all context
|
||||
systemPrompt := e.buildSystemPrompt(ctx)
|
||||
userTurn := e.RenderUserTurnContent(sessionID, query)
|
||||
|
||||
messages := []chat.Message{
|
||||
{Role: "system", Content: systemPrompt},
|
||||
{Role: "user", Content: query},
|
||||
{Role: "user", Content: userTurn},
|
||||
}
|
||||
|
||||
// Add all tool call results as context
|
||||
|
||||
+51
-41
@@ -206,19 +206,10 @@ func escapeXMLAttr(s string) string {
|
||||
}
|
||||
|
||||
// buildRuntimeContextBlock builds a metadata block with current time, session
|
||||
// info, and the *active retrieval scope for this turn*. The scope snapshot is
|
||||
// critical for multi-turn correctness: when the user switches their @mention
|
||||
// to a different KB or document between turns, earlier turns still carry
|
||||
// their own scope snapshot in history, so the model can see the scope change
|
||||
// and avoid reusing last turn's answer against the new scope.
|
||||
//
|
||||
// The detailed bound-KB metadata (capabilities, recent documents, summaries)
|
||||
// also lives here — it is turn state, not instructions, so it belongs next
|
||||
// to the user query rather than baked into the system prompt. Keeping it in
|
||||
// the user message keeps the system prompt stable/cacheable and lets the
|
||||
// model see exactly which KBs were in scope at the time of each historical
|
||||
// turn. Per-turn @mentioned MCP/Skill requirements are emitted separately via
|
||||
// buildMustUseBlock (sibling to runtime_context in the user message).
|
||||
// info, and the *active retrieval scope for this turn only*. It is injected
|
||||
// into the current user message for the LLM call and is not persisted into
|
||||
// conversation history — replayed user turns keep bare Content so stale scope
|
||||
// snapshots do not steer follow-up questions.
|
||||
//
|
||||
// Per-turn communication_instruction and answer_instruction remind the model
|
||||
// not to leak internal tool names or IDs in user-visible text, and to end the
|
||||
@@ -283,42 +274,64 @@ func buildRuntimeContextBlock(
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
// buildMustUseBlock emits per-turn @mentioned MCP/Skill requirements as a
|
||||
// sibling envelope outside runtime_context.
|
||||
// buildMustUseBlock emits a short per-turn hint when the user @mentioned MCP/Skill.
|
||||
// Tool names are not listed here — they are already in the function-calling schema.
|
||||
func buildMustUseBlock(mcpServices []*PinnedMCPServiceInfo, skills []*PinnedSkillInfo) string {
|
||||
if len(mcpServices) == 0 && len(skills) == 0 {
|
||||
return ""
|
||||
}
|
||||
var sb strings.Builder
|
||||
sb.WriteString("<must_use>\n")
|
||||
sb.WriteString(" <instruction>REQUIRED this turn: the user @selected these capabilities. ")
|
||||
sb.WriteString("For EACH listed MCP service you MUST call at least one tool from its tools= list ")
|
||||
sb.WriteString("in your FIRST tool round (before grep_chunks / knowledge_search / wiki_search). ")
|
||||
sb.WriteString("For EACH listed skill call read_skill(skill_name=...) before your final answer. ")
|
||||
sb.WriteString("The @mention means the user wants that source — do not answer using only local KB retrieval when an MCP service is listed.</instruction>\n")
|
||||
var lines []string
|
||||
for _, svc := range mcpServices {
|
||||
if svc == nil {
|
||||
continue
|
||||
}
|
||||
name := svc.Name
|
||||
if name == "" {
|
||||
name = svc.ID
|
||||
prefix := mcpToolNamePrefix(svc)
|
||||
if prefix == "" {
|
||||
continue
|
||||
}
|
||||
if len(svc.ToolNames) > 0 {
|
||||
fmt.Fprintf(&sb, " <mcp name=\"%s\" tools=\"%s\" />\n",
|
||||
escapeXMLAttr(name), escapeXMLAttr(strings.Join(svc.ToolNames, ", ")))
|
||||
} else {
|
||||
fmt.Fprintf(&sb, " <mcp name=\"%s\" />\n", escapeXMLAttr(name))
|
||||
display := svc.Name
|
||||
if display == "" {
|
||||
display = svc.ID
|
||||
}
|
||||
lines = append(lines, fmt.Sprintf("Must use MCP tools whose names start with %s (@%s) to answer the question below.", prefix, display))
|
||||
}
|
||||
for _, skill := range skills {
|
||||
if skill == nil || skill.Name == "" {
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(&sb, " <skill name=\"%s\" />\n", escapeXMLAttr(skill.Name))
|
||||
lines = append(lines, fmt.Sprintf("Must call read_skill(skill_name=\"%s\") for @Skill \"%s\" before answering.", skill.Name, skill.Name))
|
||||
}
|
||||
sb.WriteString("</must_use>")
|
||||
return sb.String()
|
||||
if len(lines) == 0 {
|
||||
return ""
|
||||
}
|
||||
return "<must_use>\n" + strings.Join(lines, "\n") + "\n</must_use>"
|
||||
}
|
||||
|
||||
// mcpToolNamePrefix returns the shared prefix for an MCP service's registered tools
|
||||
// (e.g. mcp_iwiki_ from mcp_iwiki_getdocument).
|
||||
func mcpToolNamePrefix(svc *PinnedMCPServiceInfo) string {
|
||||
if svc == nil || len(svc.ToolNames) == 0 {
|
||||
return ""
|
||||
}
|
||||
const head = "mcp_"
|
||||
for _, toolName := range svc.ToolNames {
|
||||
if !strings.HasPrefix(toolName, head) {
|
||||
continue
|
||||
}
|
||||
rest := toolName[len(head):]
|
||||
idx := strings.Index(rest, "_")
|
||||
if idx <= 0 {
|
||||
continue
|
||||
}
|
||||
return head + rest[:idx+1]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// RenderUserTurnContent builds the user-turn payload for the current LLM call
|
||||
// (runtime_context + must_use + query). Used by Execute and finalize paths only;
|
||||
// not written to rendered_content / history.
|
||||
func (e *AgentEngine) RenderUserTurnContent(sessionID, query string) string {
|
||||
runtimeCtx := buildRuntimeContextBlock(sessionID, e.knowledgeBasesInfo, e.selectedDocs)
|
||||
mustUse := buildMustUseBlock(e.pinnedMCPServices, e.pinnedSkills)
|
||||
return composeUserTurnContent(runtimeCtx, mustUse, query)
|
||||
}
|
||||
|
||||
func composeUserTurnContent(parts ...string) string {
|
||||
@@ -491,11 +504,8 @@ func (e *AgentEngine) buildMessagesWithLLMContext(
|
||||
}
|
||||
}
|
||||
|
||||
// Build user message with runtime context safety tag.
|
||||
// The runtime context carries a per-turn scope snapshot so that multi-turn
|
||||
// history preserves the (kb, pinned docs) that each earlier turn ran under;
|
||||
// this is what lets the model detect a scope switch instead of silently
|
||||
// answering the new question against last turn's retrieval.
|
||||
// Build user message with per-turn scope envelopes (current turn only).
|
||||
// Historical user messages in llmContext stay as bare Content from the DB.
|
||||
runtimeCtx := buildRuntimeContextBlock(sessionID, e.knowledgeBasesInfo, e.selectedDocs)
|
||||
mustUse := buildMustUseBlock(e.pinnedMCPServices, e.pinnedSkills)
|
||||
userMsg := chat.Message{
|
||||
|
||||
@@ -170,8 +170,9 @@ func TestBuildRuntimeContextBlock_PinnedDocuments(t *testing.T) {
|
||||
func TestBuildMustUseBlock_MCPAndSkills(t *testing.T) {
|
||||
block := buildMustUseBlock(
|
||||
[]*PinnedMCPServiceInfo{{
|
||||
ID: "mcp-1",
|
||||
Name: "ChemDB",
|
||||
ID: "mcp-1",
|
||||
Name: "ChemDB",
|
||||
ToolNames: []string{"mcp_chemdb_search"},
|
||||
}},
|
||||
[]*PinnedSkillInfo{{
|
||||
Name: "data-analysis",
|
||||
@@ -180,14 +181,14 @@ func TestBuildMustUseBlock_MCPAndSkills(t *testing.T) {
|
||||
|
||||
assert.Contains(t, block, "<must_use>")
|
||||
assert.NotContains(t, block, "<runtime_context")
|
||||
assert.Contains(t, block, "<instruction>REQUIRED this turn")
|
||||
assert.Contains(t, block, "FIRST tool round")
|
||||
assert.Contains(t, block, "read_skill")
|
||||
assert.Contains(t, block, `<mcp name="ChemDB"`)
|
||||
assert.Contains(t, block, `<skill name="data-analysis"`)
|
||||
assert.NotContains(t, block, "<instruction>")
|
||||
assert.Contains(t, block, "Must use MCP tools whose names start with mcp_chemdb_")
|
||||
assert.Contains(t, block, "@ChemDB")
|
||||
assert.Contains(t, block, `Must call read_skill(skill_name="data-analysis")`)
|
||||
assert.Contains(t, block, `@Skill "data-analysis"`)
|
||||
}
|
||||
|
||||
func TestBuildMustUseBlock_MCPToolNames(t *testing.T) {
|
||||
func TestBuildMustUseBlock_MCPToolPrefixOnly(t *testing.T) {
|
||||
block := buildMustUseBlock(
|
||||
[]*PinnedMCPServiceInfo{{
|
||||
ID: "mcp-1",
|
||||
@@ -196,5 +197,30 @@ func TestBuildMustUseBlock_MCPToolNames(t *testing.T) {
|
||||
}},
|
||||
nil,
|
||||
)
|
||||
assert.Contains(t, block, `tools="mcp_iwiki_aisearchdocument, mcp_iwiki_getdocument"`)
|
||||
assert.Contains(t, block, "mcp_iwiki_")
|
||||
assert.NotContains(t, block, "aisearchdocument")
|
||||
assert.NotContains(t, block, `tools="`)
|
||||
}
|
||||
|
||||
func TestBuildMustUseBlock_SkipsMCPWithoutTools(t *testing.T) {
|
||||
block := buildMustUseBlock(
|
||||
[]*PinnedMCPServiceInfo{{
|
||||
ID: "mcp-1",
|
||||
Name: "DisabledMCP",
|
||||
}},
|
||||
[]*PinnedSkillInfo{{Name: "data-analysis"}},
|
||||
)
|
||||
assert.Contains(t, block, `Must call read_skill(skill_name="data-analysis")`)
|
||||
assert.NotContains(t, block, "DisabledMCP")
|
||||
}
|
||||
|
||||
func TestRenderUserTurnContent_IncludesScopeBlocks(t *testing.T) {
|
||||
engine := &AgentEngine{
|
||||
knowledgeBasesInfo: []*KnowledgeBaseInfo{{ID: "kb-1", Name: "Docs"}},
|
||||
pinnedSkills: []*PinnedSkillInfo{{Name: "analysis"}},
|
||||
}
|
||||
out := engine.RenderUserTurnContent("sess-1", "hello")
|
||||
assert.Contains(t, out, "<runtime_context")
|
||||
assert.Contains(t, out, "<must_use>")
|
||||
assert.Contains(t, out, "hello")
|
||||
}
|
||||
|
||||
@@ -126,20 +126,24 @@ func (t *GrepChunksTool) Execute(ctx context.Context, args json.RawMessage) (*ty
|
||||
// bounded so the LLM context stays small regardless of regex breadth.
|
||||
const limit = 30
|
||||
|
||||
kbIDs := t.searchTargets.GetAllKnowledgeBaseIDs()
|
||||
kbTenantMap := t.searchTargets.GetKBTenantMap()
|
||||
|
||||
var allowedKnowledgeIDs []string
|
||||
for _, target := range t.searchTargets {
|
||||
if target.Type == types.SearchTargetTypeKnowledge && len(target.KnowledgeIDs) > 0 {
|
||||
allowedKnowledgeIDs = append(allowedKnowledgeIDs, target.KnowledgeIDs...)
|
||||
}
|
||||
fullKBIDs, knowledgeIDs, err := t.resolveGrepScope(ctx)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "[Tool][GrepChunks] Failed to resolve search scope: %v", err)
|
||||
return &types.ToolResult{
|
||||
Success: false,
|
||||
Error: fmt.Sprintf("Failed to resolve search scope: %v", err),
|
||||
}, err
|
||||
}
|
||||
kbIDsForMeta := fullKBIDs
|
||||
if len(kbIDsForMeta) == 0 {
|
||||
kbIDsForMeta = t.searchTargets.GetAllKnowledgeBaseIDs()
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[Tool][GrepChunks] Queries: %v, Limit: %d, KBs: %v, KnowledgeIDs: %v",
|
||||
queries, limit, kbIDs, allowedKnowledgeIDs)
|
||||
queries, limit, fullKBIDs, knowledgeIDs)
|
||||
|
||||
results, err := t.searchChunks(ctx, queries, kbIDs, allowedKnowledgeIDs, kbTenantMap)
|
||||
results, err := t.searchChunks(ctx, queries, fullKBIDs, knowledgeIDs, kbTenantMap)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "[Tool][GrepChunks] Search failed: %v", err)
|
||||
return &types.ToolResult{
|
||||
@@ -217,7 +221,7 @@ func (t *GrepChunksTool) Execute(ctx context.Context, args json.RawMessage) (*ty
|
||||
"result_count": len(chunkResults),
|
||||
"document_count": documentCount,
|
||||
"total_matches": len(finalResults),
|
||||
"knowledge_base_ids": kbIDs,
|
||||
"knowledge_base_ids": kbIDsForMeta,
|
||||
"limit": limit,
|
||||
"max_results": limit, // legacy alias
|
||||
"display_type": "grep_results",
|
||||
@@ -254,6 +258,67 @@ func (t *GrepChunksTool) regexOperatorForDialect() string {
|
||||
}
|
||||
}
|
||||
|
||||
// resolveGrepScope splits search targets into full-KB IDs vs specific knowledge IDs.
|
||||
// Tag-scoped targets are resolved to knowledge IDs so grep_chunks honors @tag scope.
|
||||
func (t *GrepChunksTool) resolveGrepScope(ctx context.Context) (fullKBIDs, knowledgeIDs []string, err error) {
|
||||
seenKB := make(map[string]bool)
|
||||
seenKnowledge := make(map[string]bool)
|
||||
for _, target := range t.searchTargets {
|
||||
if target == nil || target.KnowledgeBaseID == "" {
|
||||
continue
|
||||
}
|
||||
switch {
|
||||
case len(target.KnowledgeIDs) > 0:
|
||||
for _, kid := range target.KnowledgeIDs {
|
||||
if kid != "" && !seenKnowledge[kid] {
|
||||
seenKnowledge[kid] = true
|
||||
knowledgeIDs = append(knowledgeIDs, kid)
|
||||
}
|
||||
}
|
||||
case len(target.TagIDs) > 0:
|
||||
tenantID := target.TenantID
|
||||
if tenantID == 0 {
|
||||
tenantID = t.searchTargets.GetTenantIDForKB(target.KnowledgeBaseID)
|
||||
}
|
||||
tagKnowledgeIDs, listErr := t.listKnowledgeIDsByTags(ctx, target.KnowledgeBaseID, tenantID, target.TagIDs)
|
||||
if listErr != nil {
|
||||
return nil, nil, listErr
|
||||
}
|
||||
for _, kid := range tagKnowledgeIDs {
|
||||
if kid != "" && !seenKnowledge[kid] {
|
||||
seenKnowledge[kid] = true
|
||||
knowledgeIDs = append(knowledgeIDs, kid)
|
||||
}
|
||||
}
|
||||
default:
|
||||
if !seenKB[target.KnowledgeBaseID] {
|
||||
seenKB[target.KnowledgeBaseID] = true
|
||||
fullKBIDs = append(fullKBIDs, target.KnowledgeBaseID)
|
||||
}
|
||||
}
|
||||
}
|
||||
return fullKBIDs, knowledgeIDs, nil
|
||||
}
|
||||
|
||||
func (t *GrepChunksTool) listKnowledgeIDsByTags(
|
||||
ctx context.Context,
|
||||
kbID string,
|
||||
tenantID uint64,
|
||||
tagIDs []string,
|
||||
) ([]string, error) {
|
||||
if len(tagIDs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
var ids []string
|
||||
err := t.db.WithContext(ctx).Model(&types.Knowledge{}).
|
||||
Joins("JOIN knowledge_tag_relations ktr ON knowledges.id = ktr.knowledge_id").
|
||||
Where("knowledges.tenant_id = ? AND knowledges.knowledge_base_id = ? AND ktr.tag_id IN ? AND knowledges.deleted_at IS NULL",
|
||||
tenantID, kbID, tagIDs).
|
||||
Distinct("knowledges.id").
|
||||
Pluck("knowledges.id", &ids).Error
|
||||
return ids, err
|
||||
}
|
||||
|
||||
// searchChunks performs the database search using regex queries.
|
||||
func (t *GrepChunksTool) searchChunks(
|
||||
ctx context.Context,
|
||||
|
||||
Reference in New Issue
Block a user