Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
fix(mcp): pass embedded resources in tool results to the agent (#3766)
Captain172d0a85ab17
diff --git a/internal/agent/tools/mcp_tool.go b/internal/agent/tools/mcp_tool.goindex 918a9765b..335c7185e 100644--- a/internal/agent/tools/mcp_tool.go+++ b/internal/agent/tools/mcp_tool.go@@ -388,8 +388,8 @@ func extractContentAndImages(content []mcp.ContentItem) (text string, images []s} else if item.Data != "" {skippedImages++}- case "resource":- textParts = append(textParts, fmt.Sprintf("[Resource: %s]", item.MimeType))+ case "resource", "resource_link":+ textParts = append(textParts, resourceText(item))default:if item.Text != "" {textParts = append(textParts, item.Text)@@ -406,14 +406,37 @@ func extractContentAndImages(content []mcp.ContentItem) (text string, images []sreturn text, images, skippedImages}-// redactImageData returns a copy of content items with image Data fields replaced-// by a size indicator. This prevents large base64 strings from being stored in the-// Data map (which may be serialized to logs or SSE events).+// resourceText renders a resource item for the model: a reference to the+// resource, followed by its text when the tool embedded a text resource, so+// the content itself reaches the model.+func resourceText(item mcp.ContentItem) string {+ label := "Resource"+ if item.Type == "resource_link" {+ label = "Resource link"+ }+ ref := item.MimeType+ switch {+ case item.URI != "" && item.MimeType != "":+ ref = fmt.Sprintf("%s (%s)", item.URI, item.MimeType)+ case item.URI != "":+ ref = item.URI+ }+ placeholder := fmt.Sprintf("[%s: %s]", label, ref)+ if item.Type == "resource" && item.Text != "" {+ return placeholder + "\n" + item.Text+ }+ return placeholder+}++// redactImageData returns a copy of content items with base64 Data fields, of+// images, audio and blob resources, replaced by a size indicator. This prevents+// large base64 strings from being stored in the Data map (which may be+// serialized to logs or SSE events).func redactImageData(content []mcp.ContentItem) []mcp.ContentItem {redacted := make([]mcp.ContentItem, len(content))for i, item := range content {redacted[i] = item- if item.Type == "image" && item.Data != "" {+ if item.Data != "" {redacted[i].Data = fmt.Sprintf("[redacted, base64_len=%d]", len(item.Data))}}@@ -438,9 +461,8 @@ func extractContentText(content []mcp.ContentItem) string {mimeType = "image"}textParts = append(textParts, fmt.Sprintf("[Image: %s]", mimeType))- case "resource":- // For resources, include a reference- textParts = append(textParts, fmt.Sprintf("[Resource: %s]", item.MimeType))+ case "resource", "resource_link":+ textParts = append(textParts, resourceText(item))default:// For other types, try to include any text or dataif item.Text != "" {diff --git a/internal/agent/tools/mcp_tool_resource_test.go b/internal/agent/tools/mcp_tool_resource_test.gonew file mode 100644index 000000000..d396e8b74--- /dev/null+++ b/internal/agent/tools/mcp_tool_resource_test.go@@ -0,0 +1,45 @@+package tools++import (+ "strings"+ "testing"++ "github.com/Tencent/WeKnora/internal/mcp"+ "github.com/stretchr/testify/assert"+)++// The text of an embedded resource reaches the model after a reference to the+// resource; links and binary resources stay references.+func TestExtractContentAndImages_Resources(t *testing.T) {+ content := []mcp.ContentItem{+ {Type: "text", Text: "successfully downloaded text file"},+ {Type: "resource", URI: "repo://octo/app/contents/main.go", MimeType: "text/x-go", Text: "package main"},+ {Type: "resource", URI: "repo://octo/app/contents/logo.png", MimeType: "image/png", Data: "iVBORw0KGgo="},+ {Type: "resource_link", URI: "repo://octo/app/contents/big.log", MimeType: "text/plain", Text: "big.log"},+ }++ text, images, skipped := extractContentAndImages(content)+ assert.Equal(t, strings.Join([]string{+ "successfully downloaded text file",+ "[Resource: repo://octo/app/contents/main.go (text/x-go)]",+ "package main",+ "[Resource: repo://octo/app/contents/logo.png (image/png)]",+ "[Resource link: repo://octo/app/contents/big.log (text/plain)]",+ }, "\n"), text)+ assert.Empty(t, images)+ assert.Zero(t, skipped)++ assert.Equal(t, text, extractContentText(content), "the error path renders resources the same way")+}++// Base64 payloads of any kind are kept out of the logged content items.+func TestRedactImageData_BlobResourcesAndAudio(t *testing.T) {+ redacted := redactImageData([]mcp.ContentItem{+ {Type: "resource", MimeType: "image/png", Data: "iVBORw0KGgo="},+ {Type: "audio", MimeType: "audio/wav", Data: "YXVkaW8="},+ {Type: "resource", MimeType: "text/plain", Text: "kept"},+ })+ assert.Equal(t, "[redacted, base64_len=12]", redacted[0].Data)+ assert.Equal(t, "[redacted, base64_len=8]", redacted[1].Data)+ assert.Equal(t, "kept", redacted[2].Text)+}diff --git a/internal/mcp/client.go b/internal/mcp/client.goindex 2d047a5a9..6a688f5b8 100644--- a/internal/mcp/client.go+++ b/internal/mcp/client.go@@ -603,9 +603,18 @@ func (c *mcpGoClient) CallTool(ctx context.Context, name string, args map[stringreturn nil, fmt.Errorf("failed to call tool: %w", err)}- // Convert to our types- content := make([]ContentItem, 0, len(result.Content))- for _, item := range result.Content {+ return &CallToolResult{+ IsError: result.IsError,+ Content: toolContentItems(result.Content),+ }, nil+}++// toolContentItems converts the content of a tool result. Besides text and+// images, a tool can return audio, a resource embedded in the result (GitHub's+// get_file_contents returns the file that way) or a link to one.+func toolContentItems(items []mcp.Content) []ContentItem {+ content := make([]ContentItem, 0, len(items))+ for _, item := range items {if textContent, ok := mcp.AsTextContent(item); ok {content = append(content, ContentItem{Type: "text",@@ -617,13 +626,30 @@ func (c *mcpGoClient) CallTool(ctx context.Context, name string, args map[stringData: imageContent.Data,MimeType: imageContent.MIMEType,})+ } else if audioContent, ok := mcp.AsAudioContent(item); ok {+ content = append(content, ContentItem{+ Type: "audio",+ Data: audioContent.Data,+ MimeType: audioContent.MIMEType,+ })+ } else if resource, ok := mcp.AsEmbeddedResource(item); ok {+ resourceItem := ContentItem{Type: "resource"}+ if text, ok := mcp.AsTextResourceContents(resource.Resource); ok {+ resourceItem.URI, resourceItem.MimeType, resourceItem.Text = text.URI, text.MIMEType, text.Text+ } else if blob, ok := mcp.AsBlobResourceContents(resource.Resource); ok {+ resourceItem.URI, resourceItem.MimeType, resourceItem.Data = blob.URI, blob.MIMEType, blob.Blob+ }+ content = append(content, resourceItem)+ } else if link, ok := item.(mcp.ResourceLink); ok {+ content = append(content, ContentItem{+ Type: "resource_link",+ Text: link.Name,+ MimeType: link.MIMEType,+ URI: link.URI,+ })}}-- return &CallToolResult{- IsError: result.IsError,- Content: content,- }, nil+ return content}// ReadResource reads a resource from the MCP servicediff --git a/internal/mcp/tool_content_test.go b/internal/mcp/tool_content_test.gonew file mode 100644index 000000000..8eb79133d--- /dev/null+++ b/internal/mcp/tool_content_test.go@@ -0,0 +1,40 @@+package mcp++import (+ "testing"++ "github.com/mark3labs/mcp-go/mcp"+ "github.com/stretchr/testify/require"+)++// Tool results can carry more than text and images. GitHub's+// get_file_contents, for one, returns a short text message and the file as an+// embedded resource; dropping the resource left the agent with only the+// message.+func TestToolContentItems(t *testing.T) {+ items := toolContentItems([]mcp.Content{+ mcp.NewTextContent("successfully downloaded text file"),+ mcp.NewEmbeddedResource(mcp.TextResourceContents{+ URI: "repo://octo/app/contents/main.go",+ MIMEType: "text/x-go",+ Text: "package main",+ }),+ mcp.NewEmbeddedResource(mcp.BlobResourceContents{+ URI: "repo://octo/app/contents/logo.png",+ MIMEType: "image/png",+ Blob: "iVBORw0KGgo=",+ }),+ mcp.NewResourceLink("repo://octo/app/contents/big.log", "big.log", "", "text/plain"),+ mcp.NewImageContent("aW1n", "image/png"),+ mcp.NewAudioContent("YXVkaW8=", "audio/wav"),+ })++ require.Equal(t, []ContentItem{+ {Type: "text", Text: "successfully downloaded text file"},+ {Type: "resource", URI: "repo://octo/app/contents/main.go", MimeType: "text/x-go", Text: "package main"},+ {Type: "resource", URI: "repo://octo/app/contents/logo.png", MimeType: "image/png", Data: "iVBORw0KGgo="},+ {Type: "resource_link", URI: "repo://octo/app/contents/big.log", MimeType: "text/plain", Text: "big.log"},+ {Type: "image", Data: "aW1n", MimeType: "image/png"},+ {Type: "audio", Data: "YXVkaW8=", MimeType: "audio/wav"},+ }, items)+}diff --git a/internal/mcp/types.go b/internal/mcp/types.goindex 8316a04c0..87599e293 100644--- a/internal/mcp/types.go+++ b/internal/mcp/types.go@@ -49,10 +49,12 @@ type CallToolResult struct {// ContentItem represents a content item in tool resulttype ContentItem struct {- Type string `json:"type"` // "text", "image", "resource"+ Type string `json:"type"` // "text", "image", "audio", "resource", "resource_link"Text string `json:"text,omitempty"`Data string `json:"data,omitempty"`MimeType string `json:"mimeType,omitempty"`+ // URI identifies the resource of a "resource" or "resource_link" item.+ URI string `json:"uri,omitempty"`}// ReadResourceResult represents the result of resources/read request