feat(chat): add @Skill/@MCP mentions with scoped agent runtime
Wire per-turn @mentions for skills, MCP services, tags, and files through QA handlers into agent config, runtime_context/must_use user blocks, and tool registration. Fix tag-only scopes dropping KB tools, refresh suggested questions on mention changes, and strengthen MCP must_use so @selected services are invoked before local KB search.
This commit is contained in:
+29
-28
@@ -38,6 +38,8 @@ type AgentEngine struct {
|
||||
eventBus *event.EventBus
|
||||
knowledgeBasesInfo []*KnowledgeBaseInfo // Detailed knowledge base information for prompt
|
||||
selectedDocs []*SelectedDocumentInfo // User-selected documents (via @ mention)
|
||||
pinnedMCPServices []*PinnedMCPServiceInfo // User @mentioned MCP services for this turn
|
||||
pinnedSkills []*PinnedSkillInfo // User @mentioned skills for this turn
|
||||
sessionID string // Session ID for logging and event emission
|
||||
systemPromptTemplate string // System prompt template (optional, uses default if empty)
|
||||
skillsManager *skills.Manager // Skills manager for Progressive Disclosure (optional)
|
||||
@@ -93,6 +95,32 @@ func NewAgentEngine(
|
||||
return engine
|
||||
}
|
||||
|
||||
// SetPinnedMentions sets per-turn @mention scope for MCP services and skills.
|
||||
func (e *AgentEngine) SetPinnedMentions(mcpServices []*PinnedMCPServiceInfo, skills []*PinnedSkillInfo) {
|
||||
e.pinnedMCPServices = mcpServices
|
||||
e.pinnedSkills = skills
|
||||
}
|
||||
|
||||
func (e *AgentEngine) systemPromptOptions(ctx context.Context) *BuildSystemPromptOptions {
|
||||
opts := &BuildSystemPromptOptions{
|
||||
Language: types.LanguageNameFromContext(ctx),
|
||||
Config: e.appConfig,
|
||||
}
|
||||
if e.skillsManager != nil && e.skillsManager.IsEnabled() {
|
||||
opts.SkillsMetadata = e.skillsManager.GetAllMetadata()
|
||||
}
|
||||
return opts
|
||||
}
|
||||
|
||||
func (e *AgentEngine) buildSystemPrompt(ctx context.Context) string {
|
||||
return BuildSystemPromptWithOptions(
|
||||
e.knowledgeBasesInfo,
|
||||
e.config.WebSearchEnabled,
|
||||
e.systemPromptOptions(ctx),
|
||||
e.systemPromptTemplate,
|
||||
)
|
||||
}
|
||||
|
||||
// NewAgentEngineWithSkills creates a new agent engine with skills support
|
||||
func NewAgentEngineWithSkills(
|
||||
config *types.AgentConfig,
|
||||
@@ -220,34 +248,7 @@ func (e *AgentEngine) Execute(
|
||||
|
||||
// Build system prompt using progressive RAG prompt
|
||||
// If skills are enabled, include skills metadata (Level 1 - Progressive Disclosure)
|
||||
// Extract user language from context for prompt placeholder
|
||||
language := types.LanguageNameFromContext(ctx)
|
||||
var systemPrompt string
|
||||
if e.skillsManager != nil && e.skillsManager.IsEnabled() {
|
||||
skillsMetadata := e.skillsManager.GetAllMetadata()
|
||||
systemPrompt = BuildSystemPromptWithOptions(
|
||||
e.knowledgeBasesInfo,
|
||||
e.config.WebSearchEnabled,
|
||||
e.selectedDocs,
|
||||
&BuildSystemPromptOptions{
|
||||
SkillsMetadata: skillsMetadata,
|
||||
Language: language,
|
||||
Config: e.appConfig,
|
||||
},
|
||||
e.systemPromptTemplate,
|
||||
)
|
||||
} else {
|
||||
systemPrompt = BuildSystemPromptWithOptions(
|
||||
e.knowledgeBasesInfo,
|
||||
e.config.WebSearchEnabled,
|
||||
e.selectedDocs,
|
||||
&BuildSystemPromptOptions{
|
||||
Language: language,
|
||||
Config: e.appConfig,
|
||||
},
|
||||
e.systemPromptTemplate,
|
||||
)
|
||||
}
|
||||
systemPrompt := e.buildSystemPrompt(ctx)
|
||||
logger.Debugf(ctx, "[Agent] SystemPrompt: %d chars", len(systemPrompt))
|
||||
|
||||
// Initialize messages with history
|
||||
|
||||
@@ -31,17 +31,7 @@ func (e *AgentEngine) streamFinalAnswerToEventBus(
|
||||
})
|
||||
|
||||
// Build messages with all context
|
||||
language := types.LanguageNameFromContext(ctx)
|
||||
systemPrompt := BuildSystemPromptWithOptions(
|
||||
e.knowledgeBasesInfo,
|
||||
e.config.WebSearchEnabled,
|
||||
e.selectedDocs,
|
||||
&BuildSystemPromptOptions{
|
||||
Language: language,
|
||||
Config: e.appConfig,
|
||||
},
|
||||
e.systemPromptTemplate,
|
||||
)
|
||||
systemPrompt := e.buildSystemPrompt(ctx)
|
||||
|
||||
messages := []chat.Message{
|
||||
{Role: "system", Content: systemPrompt},
|
||||
|
||||
@@ -217,7 +217,8 @@ func escapeXMLAttr(s string) string {
|
||||
// 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.
|
||||
// turn. Per-turn @mentioned MCP/Skill requirements are emitted separately via
|
||||
// buildMustUseBlock (sibling to runtime_context in the user message).
|
||||
//
|
||||
// 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
|
||||
@@ -232,7 +233,7 @@ func buildRuntimeContextBlock(
|
||||
docs []*SelectedDocumentInfo,
|
||||
) string {
|
||||
var sb strings.Builder
|
||||
sb.WriteString("<runtime_context note=\"turn metadata; follow communication_instruction and answer_instruction\">\n")
|
||||
sb.WriteString("<runtime_context scope=\"this_turn\">\n")
|
||||
fmt.Fprintf(&sb, " <current_time>%s</current_time>\n", time.Now().Format(time.RFC3339))
|
||||
fmt.Fprintf(&sb, " <session>%s</session>\n", escapeXMLAttr(sessionID))
|
||||
|
||||
@@ -261,11 +262,18 @@ func buildRuntimeContextBlock(
|
||||
if title == "" {
|
||||
title = d.KnowledgeID
|
||||
}
|
||||
fmt.Fprintf(&sb, " <document knowledge_id=\"%s\" title=\"%s\" />\n",
|
||||
escapeXMLAttr(d.KnowledgeID), escapeXMLAttr(title))
|
||||
if d.FileType != "" {
|
||||
fmt.Fprintf(&sb, " <document knowledge_id=\"%s\" title=\"%s\" file_type=\"%s\" />\n",
|
||||
escapeXMLAttr(d.KnowledgeID), escapeXMLAttr(title), escapeXMLAttr(d.FileType))
|
||||
} else {
|
||||
fmt.Fprintf(&sb, " <document knowledge_id=\"%s\" title=\"%s\" />\n",
|
||||
escapeXMLAttr(d.KnowledgeID), escapeXMLAttr(title))
|
||||
}
|
||||
}
|
||||
sb.WriteString(" </pinned_documents>\n")
|
||||
sb.WriteString(" <note>The pinned-document set above is authoritative for THIS turn. If an earlier turn in this conversation analysed a different document, do NOT reuse that analysis — re-query against the current scope.</note>\n")
|
||||
sb.WriteString(" <note>The pinned-document set above is authoritative for THIS turn. ")
|
||||
sb.WriteString("Prioritize retrieving content from these documents (e.g. list_knowledge_chunks with the knowledge_id). ")
|
||||
sb.WriteString("If an earlier turn analysed a different document, do NOT reuse that analysis — re-query against the current scope.</note>\n")
|
||||
}
|
||||
|
||||
sb.WriteString(" <communication_instruction>Do not use internal tool names or identifiers in your answers or in Thought. Say \"keyword retrieval\" instead of grep_chunks, \"semantic retrieval\" instead of knowledge_search, \"browse full document\" instead of list_knowledge_chunks; likewise never expose chunk_id, knowledge_id, or other internal IDs—refer to documents by title or name.</communication_instruction>\n")
|
||||
@@ -275,6 +283,54 @@ func buildRuntimeContextBlock(
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
// buildMustUseBlock emits per-turn @mentioned MCP/Skill requirements as a
|
||||
// sibling envelope outside runtime_context.
|
||||
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")
|
||||
for _, svc := range mcpServices {
|
||||
if svc == nil {
|
||||
continue
|
||||
}
|
||||
name := svc.Name
|
||||
if name == "" {
|
||||
name = svc.ID
|
||||
}
|
||||
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))
|
||||
}
|
||||
}
|
||||
for _, skill := range skills {
|
||||
if skill == nil || skill.Name == "" {
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(&sb, " <skill name=\"%s\" />\n", escapeXMLAttr(skill.Name))
|
||||
}
|
||||
sb.WriteString("</must_use>")
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
func composeUserTurnContent(parts ...string) string {
|
||||
nonEmpty := make([]string, 0, len(parts))
|
||||
for _, part := range parts {
|
||||
if strings.TrimSpace(part) != "" {
|
||||
nonEmpty = append(nonEmpty, part)
|
||||
}
|
||||
}
|
||||
return strings.Join(nonEmpty, "\n\n")
|
||||
}
|
||||
|
||||
// listToolNames returns tool.function names for logging
|
||||
func listToolNames(ts []chat.Tool) []string {
|
||||
names := make([]string, 0, len(ts))
|
||||
@@ -441,9 +497,10 @@ func (e *AgentEngine) buildMessagesWithLLMContext(
|
||||
// this is what lets the model detect a scope switch instead of silently
|
||||
// answering the new question against last turn's retrieval.
|
||||
runtimeCtx := buildRuntimeContextBlock(sessionID, e.knowledgeBasesInfo, e.selectedDocs)
|
||||
mustUse := buildMustUseBlock(e.pinnedMCPServices, e.pinnedSkills)
|
||||
userMsg := chat.Message{
|
||||
Role: "user",
|
||||
Content: runtimeCtx + "\n\n" + currentQuery,
|
||||
Content: composeUserTurnContent(runtimeCtx, mustUse, currentQuery),
|
||||
Images: imageURLs,
|
||||
}
|
||||
messages = append(messages, userMsg)
|
||||
|
||||
@@ -147,3 +147,54 @@ func TestAppendToolResults_PreservesReasoningContent(t *testing.T) {
|
||||
assert.Equal(t, "thinking", out[2].ReasoningContent)
|
||||
})
|
||||
}
|
||||
|
||||
func TestBuildRuntimeContextBlock_PinnedDocuments(t *testing.T) {
|
||||
block := buildRuntimeContextBlock(
|
||||
"sess-1",
|
||||
nil,
|
||||
[]*SelectedDocumentInfo{{
|
||||
KnowledgeID: "kid-1",
|
||||
Title: "Report.pdf",
|
||||
FileType: "pdf",
|
||||
}},
|
||||
)
|
||||
|
||||
assert.Contains(t, block, "<pinned_documents")
|
||||
assert.Contains(t, block, `knowledge_id="kid-1"`)
|
||||
assert.Contains(t, block, `title="Report.pdf"`)
|
||||
assert.Contains(t, block, `file_type="pdf"`)
|
||||
assert.Contains(t, block, "list_knowledge_chunks")
|
||||
assert.NotContains(t, block, "<must_use>")
|
||||
}
|
||||
|
||||
func TestBuildMustUseBlock_MCPAndSkills(t *testing.T) {
|
||||
block := buildMustUseBlock(
|
||||
[]*PinnedMCPServiceInfo{{
|
||||
ID: "mcp-1",
|
||||
Name: "ChemDB",
|
||||
}},
|
||||
[]*PinnedSkillInfo{{
|
||||
Name: "data-analysis",
|
||||
}},
|
||||
)
|
||||
|
||||
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"`)
|
||||
}
|
||||
|
||||
func TestBuildMustUseBlock_MCPToolNames(t *testing.T) {
|
||||
block := buildMustUseBlock(
|
||||
[]*PinnedMCPServiceInfo{{
|
||||
ID: "mcp-1",
|
||||
Name: "iwiki",
|
||||
ToolNames: []string{"mcp_iwiki_aisearchdocument", "mcp_iwiki_getdocument"},
|
||||
}},
|
||||
nil,
|
||||
)
|
||||
assert.Contains(t, block, `tools="mcp_iwiki_aisearchdocument, mcp_iwiki_getdocument"`)
|
||||
}
|
||||
|
||||
+21
-43
@@ -61,8 +61,8 @@ type RecentDocInfo struct {
|
||||
FAQAnswers []string
|
||||
}
|
||||
|
||||
// SelectedDocumentInfo contains summary information about a user-selected document (via @ mention)
|
||||
// Only metadata is included; content will be fetched via tools when needed
|
||||
// SelectedDocumentInfo contains summary information about a user-selected document (via @ mention).
|
||||
// Injected into the user message runtime_context (pinned_documents); content is fetched via tools.
|
||||
type SelectedDocumentInfo struct {
|
||||
KnowledgeID string // Knowledge ID
|
||||
KnowledgeBaseID string // Knowledge base ID
|
||||
@@ -71,6 +71,20 @@ type SelectedDocumentInfo struct {
|
||||
FileType string // File type (pdf, docx, etc.)
|
||||
}
|
||||
|
||||
// PinnedMCPServiceInfo describes an MCP service explicitly @mentioned for this turn.
|
||||
type PinnedMCPServiceInfo struct {
|
||||
ID string
|
||||
Name string
|
||||
Description string
|
||||
ToolNames []string // Registered tool.function names for this service (mcp_{service}_{tool})
|
||||
}
|
||||
|
||||
// PinnedSkillInfo describes a preloaded skill explicitly @mentioned for this turn.
|
||||
type PinnedSkillInfo struct {
|
||||
Name string
|
||||
Description string
|
||||
}
|
||||
|
||||
// KnowledgeBaseInfo contains essential information about a knowledge base for agent prompt
|
||||
type KnowledgeBaseInfo struct {
|
||||
ID string
|
||||
@@ -159,7 +173,7 @@ func formatKnowledgeBaseList(kbInfos []*KnowledgeBaseInfo) string {
|
||||
} else {
|
||||
b.WriteString("<recent_documents>\n")
|
||||
for j, doc := range kb.RecentDocs {
|
||||
if j >= 10 {
|
||||
if j >= 2 {
|
||||
break
|
||||
}
|
||||
docName := doc.Title
|
||||
@@ -194,6 +208,9 @@ func formatKnowledgeBaseList(kbInfos []*KnowledgeBaseInfo) string {
|
||||
// placeholder is expanded to a short pointer so legacy / custom
|
||||
// templates that still reference `{{knowledge_bases}}` degrade
|
||||
// gracefully instead of dumping the detail twice.
|
||||
// - `<must_use>` is NOT a placeholder — when the user @mentions MCP/Skill,
|
||||
// observe.buildMustUseBlock injects it as a sibling block in the user
|
||||
// message; system prompts document it by convention (see agent_system_prompt.yaml).
|
||||
func renderPromptPlaceholders(template string, knowledgeBases []*KnowledgeBaseInfo) string {
|
||||
result := template
|
||||
|
||||
@@ -245,38 +262,6 @@ func formatSkillsMetadata(skillsMetadata []*skills.SkillMetadata) string {
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
// formatSelectedDocuments formats selected documents for the prompt (summary only, no content)
|
||||
func formatSelectedDocuments(docs []*SelectedDocumentInfo) string {
|
||||
if len(docs) == 0 {
|
||||
return ""
|
||||
}
|
||||
|
||||
var builder strings.Builder
|
||||
builder.WriteString("\n### User Selected Documents (via @ mention)\n")
|
||||
builder.WriteString("The user has explicitly selected the following documents. ")
|
||||
builder.WriteString("**You should prioritize searching and retrieving information from these documents when answering.**\n")
|
||||
builder.WriteString("Use `list_knowledge_chunks` with the provided Knowledge IDs to fetch their content.\n\n")
|
||||
|
||||
builder.WriteString("| # | Document Name | Type | Knowledge ID |\n")
|
||||
builder.WriteString("|---|---------------|------|---------------|\n")
|
||||
|
||||
for i, doc := range docs {
|
||||
title := doc.Title
|
||||
if title == "" {
|
||||
title = doc.FileName
|
||||
}
|
||||
fileType := doc.FileType
|
||||
if fileType == "" {
|
||||
fileType = "-"
|
||||
}
|
||||
builder.WriteString(fmt.Sprintf("| %d | %s | %s | `%s` |\n",
|
||||
i+1, title, fileType, doc.KnowledgeID))
|
||||
}
|
||||
builder.WriteString("\n")
|
||||
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
// renderPromptPlaceholdersWithStatus renders placeholders including web search status
|
||||
// Supported placeholders:
|
||||
// - {{knowledge_bases}}
|
||||
@@ -320,17 +305,15 @@ type BuildSystemPromptOptions struct {
|
||||
func BuildSystemPrompt(
|
||||
knowledgeBases []*KnowledgeBaseInfo,
|
||||
webSearchEnabled bool,
|
||||
selectedDocs []*SelectedDocumentInfo,
|
||||
systemPromptTemplate ...string,
|
||||
) string {
|
||||
return BuildSystemPromptWithOptions(knowledgeBases, webSearchEnabled, selectedDocs, nil, systemPromptTemplate...)
|
||||
return BuildSystemPromptWithOptions(knowledgeBases, webSearchEnabled, nil, systemPromptTemplate...)
|
||||
}
|
||||
|
||||
// BuildSystemPromptWithOptions builds the system prompt with additional options like skills
|
||||
func BuildSystemPromptWithOptions(
|
||||
knowledgeBases []*KnowledgeBaseInfo,
|
||||
webSearchEnabled bool,
|
||||
selectedDocs []*SelectedDocumentInfo,
|
||||
options *BuildSystemPromptOptions,
|
||||
systemPromptTemplate ...string,
|
||||
) string {
|
||||
@@ -361,11 +344,6 @@ func BuildSystemPromptWithOptions(
|
||||
}
|
||||
basePrompt = renderPromptPlaceholdersWithStatus(template, knowledgeBases, webSearchEnabled, currentTime, language)
|
||||
|
||||
// Append selected documents section if any
|
||||
if len(selectedDocs) > 0 {
|
||||
basePrompt += formatSelectedDocuments(selectedDocs)
|
||||
}
|
||||
|
||||
// Append skills metadata if available (Level 1 - Progressive Disclosure)
|
||||
if options != nil && len(options.SkillsMetadata) > 0 {
|
||||
basePrompt += formatSkillsMetadata(options.SkillsMetadata)
|
||||
|
||||
@@ -512,7 +512,7 @@ func (t *KnowledgeSearchTool) concurrentSearchByTargets(
|
||||
var fullKBIDs []string
|
||||
var knowledgeTargets []*types.SearchTarget
|
||||
for _, st := range targets {
|
||||
if st.Type == types.SearchTargetTypeKnowledgeBase {
|
||||
if st.Type == types.SearchTargetTypeKnowledgeBase && len(st.TagIDs) == 0 {
|
||||
fullKBIDs = append(fullKBIDs, st.KnowledgeBaseID)
|
||||
} else {
|
||||
knowledgeTargets = append(knowledgeTargets, st)
|
||||
@@ -566,6 +566,7 @@ func (t *KnowledgeSearchTool) concurrentSearchByTargets(
|
||||
VectorThreshold: vectorThreshold,
|
||||
KeywordThreshold: keywordThreshold,
|
||||
KnowledgeIDs: st.KnowledgeIDs,
|
||||
TagIDs: st.TagIDs,
|
||||
}
|
||||
kbResults, err := t.knowledgeBaseService.HybridSearch(ctx, st.KnowledgeBaseID, searchParams)
|
||||
if err != nil {
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -520,6 +521,30 @@ func RegisterMCPTools(
|
||||
return nil
|
||||
}
|
||||
|
||||
// MCPToolNamesByServiceID returns registered MCP tool names grouped by service ID.
|
||||
func MCPToolNamesByServiceID(registry *ToolRegistry) map[string][]string {
|
||||
if registry == nil {
|
||||
return nil
|
||||
}
|
||||
out := make(map[string][]string)
|
||||
for _, name := range registry.ListTools() {
|
||||
tool, err := registry.GetTool(name)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
mcpTool, ok := tool.(*MCPTool)
|
||||
if !ok || mcpTool.service == nil {
|
||||
continue
|
||||
}
|
||||
sid := mcpTool.service.ID
|
||||
out[sid] = append(out[sid], name)
|
||||
}
|
||||
for sid := range out {
|
||||
sort.Strings(out[sid])
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// GetMCPToolsInfo returns information about available MCP tools
|
||||
func GetMCPToolsInfo(
|
||||
ctx context.Context,
|
||||
|
||||
Reference in New Issue
Block a user