fix(mcp): return accessible image URLs from existing tools (#3650)
* fix(mcp): return accessible image URLs from existing tools * fix(mcp): resolve resource URLs via binding lookup and cover shared KBs - Look up the KBs that bind each reference instead of scanning every allowed KB, and cache per-KB grants for the call. Unrestricted endpoints accept any KB the caller can view, so ask answers drawing on agent-selected shared KBs get links too. - Share grant/owner-tenant resolution with scopedKBContext via authorizeKB; log non-denial authorization errors. - Drop the redundant resource-catalog re-wrap; both sources are already wrapped. - Skip the structured-content round trip when no storage reference is present, rewrite non-object results, and log marshal/decode failures. - Quote ask image lines with strconv.Quote so & stays literal, and never cut an excerpt inside a storage reference.main
parent
e87607e852
commit
2e712a97a1
|
|
@ -0,0 +1,240 @@
|
|||
package mcpserver
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/application/access"
|
||||
filesvc "github.com/Tencent/WeKnora/internal/application/service/file"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/storageurl"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
secutils "github.com/Tencent/WeKnora/internal/utils"
|
||||
"github.com/mark3labs/mcp-go/mcp"
|
||||
)
|
||||
|
||||
// resourceBindingLookup is the catalog surface the resolver needs: the
|
||||
// authoritative per-KB check plus the reverse lookup that names candidate KBs.
|
||||
type resourceBindingLookup interface {
|
||||
interfaces.KBResourceLookup
|
||||
interfaces.MessageFileBindingLookup
|
||||
}
|
||||
|
||||
// rewriteResourceURLs is the outbound boundary shared by the existing MCP
|
||||
// tools. Like IM, external MCP hosts cannot fetch private storage references.
|
||||
// Use the common URL rewriter, with an additional per-resource authorization
|
||||
// gate: a URL mentioned in editable chunk/wiki/answer text is not a grant.
|
||||
func (s *Server) rewriteResourceURLs(
|
||||
ctx context.Context, ep *types.MCPEndpoint, result *mcp.CallToolResult,
|
||||
) *mcp.CallToolResult {
|
||||
if result == nil || result.IsError || s.resourceCatalog == nil {
|
||||
return result
|
||||
}
|
||||
bindings, ok := s.resourceCatalog.(resourceBindingLookup)
|
||||
if !ok {
|
||||
return result
|
||||
}
|
||||
resolver := &resourceURLResolver{
|
||||
server: s, ctx: ctx, endpoint: ep, bindings: bindings,
|
||||
kbs: make(map[string]*resourceKBScope),
|
||||
files: make(map[resourceStorageKey]interfaces.FileService),
|
||||
}
|
||||
rewriter := storageurl.NewRewriter(resolver, "MCP")
|
||||
out := *result
|
||||
out.Content = append([]mcp.Content(nil), result.Content...)
|
||||
for i, content := range out.Content {
|
||||
if text, ok := content.(mcp.TextContent); ok {
|
||||
text.Text = rewriter.String(ctx, text.Text)
|
||||
out.Content[i] = text
|
||||
}
|
||||
}
|
||||
if result.StructuredContent != nil {
|
||||
out.StructuredContent = rewriteStructuredContent(ctx, rewriter, result.StructuredContent)
|
||||
}
|
||||
return &out
|
||||
}
|
||||
|
||||
// rewriteStructuredContent rewrites a JSON copy of a tool's structured result.
|
||||
// Agent tools use typed slices/maps (including []askReference and
|
||||
// []map[string]string), so the wire form is normalized for the rewriter
|
||||
// without mutating service objects or persisted messages.
|
||||
func rewriteStructuredContent(ctx context.Context, rewriter *storageurl.Rewriter, value any) any {
|
||||
data, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "[MCP] structured result left unrewritten: marshal failed: %v", err)
|
||||
return value
|
||||
}
|
||||
if !storageurl.Pattern.Match(data) {
|
||||
return value
|
||||
}
|
||||
var decoded any
|
||||
decoder := json.NewDecoder(bytes.NewReader(data))
|
||||
decoder.UseNumber() // Preserve integer IDs/counters without float64 rounding.
|
||||
if err := decoder.Decode(&decoded); err != nil {
|
||||
logger.Warnf(ctx, "[MCP] structured result left unrewritten: decode failed: %v", err)
|
||||
return value
|
||||
}
|
||||
return rewriter.CopyValue(ctx, decoded)
|
||||
}
|
||||
|
||||
type resourceStorageKey struct {
|
||||
tenantID uint64
|
||||
backendID string
|
||||
provider string
|
||||
}
|
||||
|
||||
// resourceKBScope is one knowledge base's authorization, resolved at most once
|
||||
// per tool call. A nil grant records a denial.
|
||||
type resourceKBScope struct {
|
||||
grant *access.KBAccess
|
||||
ctx context.Context
|
||||
}
|
||||
|
||||
type resourceURLResolver struct {
|
||||
server *Server
|
||||
ctx context.Context
|
||||
endpoint *types.MCPEndpoint
|
||||
bindings resourceBindingLookup
|
||||
kbs map[string]*resourceKBScope
|
||||
files map[resourceStorageKey]interfaces.FileService
|
||||
}
|
||||
|
||||
// ResolveFileService implements storageurl.Resolver. Failure leaves the
|
||||
// original reference untouched, just as on REST/IM, without failing the answer.
|
||||
//
|
||||
// The catalog's reverse lookup names the KBs that bind the reference, so the
|
||||
// cost is independent of how many KBs the endpoint can reach. Each candidate
|
||||
// must still pass the endpoint scope, the caller's grant and ResolveKBFile.
|
||||
func (r *resourceURLResolver) ResolveFileService(reference string) interfaces.FileService {
|
||||
for _, kbID := range r.boundKnowledgeBases(reference) {
|
||||
scope := r.knowledgeBaseScope(kbID)
|
||||
if scope.grant == nil {
|
||||
continue
|
||||
}
|
||||
file, err := access.ResolveKBFile(
|
||||
r.ctx, scope.grant, kbID, reference, r.server.resourceCatalog, r.bindings,
|
||||
)
|
||||
if err != nil {
|
||||
logResourceAccessError(r.ctx, "authorize", kbID, err)
|
||||
continue
|
||||
}
|
||||
return r.fileService(scope.ctx, file)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// boundKnowledgeBases returns the live KBs that explicitly bind reference under
|
||||
// its owner tenant. Legacy provider paths carry their owner in the path.
|
||||
func (r *resourceURLResolver) boundKnowledgeBases(reference string) []string {
|
||||
physical, resource, err := r.server.resourceCatalog.ResolvePath(r.ctx, reference)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
owner := secutils.ParseTenantIDFromStoragePath(physical)
|
||||
if resource != nil {
|
||||
owner = resource.TenantID
|
||||
}
|
||||
if owner == 0 {
|
||||
return nil
|
||||
}
|
||||
origins, err := r.bindings.GetMessageFileBindings(r.ctx, owner, reference, "")
|
||||
if err != nil {
|
||||
logger.Warnf(r.ctx, "[MCP] failed to look up resource bindings: %v", err)
|
||||
return nil
|
||||
}
|
||||
if origins == nil {
|
||||
return nil
|
||||
}
|
||||
return origins.KnowledgeBaseIDs
|
||||
}
|
||||
|
||||
// knowledgeBaseScope authorizes one KB for this endpoint. A restricted endpoint
|
||||
// accepts only its allowlist; an unrestricted one accepts any KB the caller can
|
||||
// view, which covers the shared KBs `ask` reaches through the agent's own KB
|
||||
// selection. Owned and shared KBs alike go through the same viewer grant.
|
||||
func (r *resourceURLResolver) knowledgeBaseScope(kbID string) *resourceKBScope {
|
||||
if scope, ok := r.kbs[kbID]; ok {
|
||||
return scope
|
||||
}
|
||||
scope := &resourceKBScope{}
|
||||
r.kbs[kbID] = scope
|
||||
if r.endpoint.RestrictsKnowledgeBases() && !slices.Contains(r.endpoint.KnowledgeBaseIDs, kbID) {
|
||||
return scope
|
||||
}
|
||||
kb, err := r.server.kbService.GetKnowledgeBaseByIDOnly(r.ctx, kbID)
|
||||
if err != nil || kb == nil {
|
||||
return scope
|
||||
}
|
||||
grant, ctx, err := r.server.authorizeKB(r.ctx, kb, types.OrgRoleViewer)
|
||||
if err != nil {
|
||||
logResourceAccessError(r.ctx, "resolve grant", kbID, err)
|
||||
return scope
|
||||
}
|
||||
scope.grant, scope.ctx = grant, ctx
|
||||
return scope
|
||||
}
|
||||
|
||||
// logResourceAccessError surfaces infrastructure failures; plain denials are
|
||||
// expected for references the caller may not see and stay quiet.
|
||||
func logResourceAccessError(ctx context.Context, step, kbID string, err error) {
|
||||
if errors.Is(err, access.ErrForbidden) || errors.Is(err, access.ErrNotFound) ||
|
||||
errors.Is(err, access.ErrUnauthorized) {
|
||||
return
|
||||
}
|
||||
logger.Warnf(ctx, "[MCP] resource URL %s failed for knowledge base %s: %v", step, kbID, err)
|
||||
}
|
||||
|
||||
// fileService opens the owner's storage. ctx comes from authorizeKB, so it
|
||||
// already carries the owner's TenantInfo for shared knowledge bases.
|
||||
func (r *resourceURLResolver) fileService(ctx context.Context, file access.FileAccess) interfaces.FileService {
|
||||
tenant, _ := types.TenantInfoFromContext(ctx)
|
||||
if tenant == nil || tenant.ID != file.OwnerTenantID {
|
||||
return nil
|
||||
}
|
||||
backendID, _, _ := types.ParseStorageBackendPath(file.Path)
|
||||
if file.StorageBackendID != "" {
|
||||
backendID = file.StorageBackendID
|
||||
}
|
||||
key := resourceStorageKey{file.OwnerTenantID, backendID, types.ParseProviderScheme(file.Path)}
|
||||
fileService := r.files[key]
|
||||
if fileService == nil {
|
||||
global := r.server.fileService
|
||||
if backendID != "" {
|
||||
// A missing or disabled explicit backend must not select an unrelated
|
||||
// global bucket just because its provider name happens to match.
|
||||
if r.server.storageResolver == nil {
|
||||
return nil
|
||||
}
|
||||
global = nil
|
||||
}
|
||||
// Both the backend resolver and the global service are already wrapped
|
||||
// by the resource catalog, which mints /r/<token> links for
|
||||
// resource:// handles when APP_EXTERNAL_URL is configured.
|
||||
var ok bool
|
||||
fileService, _, ok = filesvc.ResolveTenantFileServiceWithFallback(
|
||||
ctx, "MCP resource URL", tenant, backendID, key.provider, storageurl.LocalStorageBaseDir(),
|
||||
r.server.storageResolver, global,
|
||||
)
|
||||
if !ok || fileService == nil {
|
||||
return nil
|
||||
}
|
||||
r.files[key] = fileService
|
||||
}
|
||||
return &resourceURLFileService{FileService: fileService, ctx: ctx}
|
||||
}
|
||||
|
||||
// Carry the authorized owner's context through the shared rewriter, which
|
||||
// otherwise passes the original endpoint tenant to GetFileURL.
|
||||
type resourceURLFileService struct {
|
||||
interfaces.FileService
|
||||
ctx context.Context
|
||||
}
|
||||
|
||||
func (s *resourceURLFileService) GetFileURL(_ context.Context, reference string) (string, error) {
|
||||
return s.FileService.GetFileURL(s.ctx, strings.TrimSpace(reference))
|
||||
}
|
||||
|
|
@ -0,0 +1,332 @@
|
|||
package mcpserver
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/application/repository"
|
||||
"github.com/Tencent/WeKnora/internal/application/service"
|
||||
filesvc "github.com/Tencent/WeKnora/internal/application/service/file"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/mark3labs/mcp-go/mcp"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
type resourceURLFixture struct {
|
||||
srv *Server
|
||||
ctx context.Context
|
||||
ep *types.MCPEndpoint
|
||||
db *gorm.DB
|
||||
ref string
|
||||
path string
|
||||
files *resourceURLFiles
|
||||
storage *resourceURLStorage
|
||||
}
|
||||
|
||||
type resourceURLFiles struct {
|
||||
interfaces.FileService
|
||||
calls int
|
||||
path string
|
||||
tenant uint64
|
||||
tenantInfo uint64
|
||||
url string
|
||||
err error
|
||||
}
|
||||
|
||||
func (s *resourceURLFiles) GetFileURL(ctx context.Context, path string) (string, error) {
|
||||
s.calls++
|
||||
s.path = path
|
||||
s.tenant = types.MustTenantIDFromContext(ctx)
|
||||
if info, ok := types.TenantInfoFromContext(ctx); ok {
|
||||
s.tenantInfo = info.ID
|
||||
}
|
||||
return s.url, s.err
|
||||
}
|
||||
|
||||
type resourceURLStorage struct {
|
||||
interfaces.StorageBackendResolver
|
||||
files interfaces.FileService
|
||||
catalog interfaces.ResourceCatalog
|
||||
err error
|
||||
calls int
|
||||
tenant uint64
|
||||
backend string
|
||||
}
|
||||
|
||||
func (s *resourceURLStorage) ResolveFileService(
|
||||
_ context.Context, tenant *types.Tenant, backend, provider, _ string,
|
||||
) (interfaces.FileService, string, error) {
|
||||
s.calls++
|
||||
s.tenant = tenant.ID
|
||||
s.backend = backend
|
||||
// Like StorageBackendService, wrap per call so APP_EXTERNAL_URL is read then.
|
||||
return filesvc.NewResourceCatalogFileService(s.files, s.catalog), provider, s.err
|
||||
}
|
||||
|
||||
// catalogWrapped mirrors initFileService, which decorates the global service.
|
||||
func (f *resourceURLFixture) catalogWrapped() interfaces.FileService {
|
||||
return filesvc.NewResourceCatalogFileService(f.files, f.srv.resourceCatalog)
|
||||
}
|
||||
|
||||
// The real binding repository distinguishes extracted images from unowned
|
||||
// references and verifies that both the document and KB are still live.
|
||||
func newResourceURLFixture(t *testing.T) *resourceURLFixture {
|
||||
t.Helper()
|
||||
t.Setenv("APP_EXTERNAL_URL", "https://weknora.example/prefix")
|
||||
db, err := gorm.Open(sqlite.Open(filepath.Join(t.TempDir(), "images.db")), &gorm.Config{
|
||||
Logger: logger.Default.LogMode(logger.Silent),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
sqlDB, err := db.DB()
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = sqlDB.Close() })
|
||||
require.NoError(t, db.AutoMigrate(
|
||||
&types.StoredResource{}, &types.ResourceBinding{}, &types.ResourceAccessGrant{},
|
||||
&types.Knowledge{}, &types.KnowledgeBase{}, &types.Chunk{}, &types.StorageBackend{},
|
||||
))
|
||||
kb := &types.KnowledgeBase{ID: "kb-1", TenantID: 2, Name: "Shared"}
|
||||
require.NoError(t, db.Create(kb).Error)
|
||||
require.NoError(t, db.Create(&types.Knowledge{
|
||||
ID: "doc-1", TenantID: 2, KnowledgeBaseID: kb.ID, Type: "file",
|
||||
}).Error)
|
||||
catalog := service.NewResourceCatalog(repository.NewResourceRepository(db))
|
||||
path := "local://2/exports/figure.png"
|
||||
ref, err := catalog.Register(context.Background(), 2, path, interfaces.ResourceRegistration{
|
||||
Kind: "image", MimeType: "image/png", OriginalName: "figure.png",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, catalog.Bind(
|
||||
context.Background(), ref, types.ResourceOwnerKnowledge, "doc-1", types.ResourceRelationExtractedImage,
|
||||
))
|
||||
files := &resourceURLFiles{url: "https://storage.example/figure.png?signature=test"}
|
||||
storage := &resourceURLStorage{files: files, catalog: catalog}
|
||||
srv := &Server{
|
||||
kbService: &stubKBService{kbs: map[string]*types.KnowledgeBase{kb.ID: kb}},
|
||||
kbShareService: &stubKBShareService{shared: map[string]types.OrgMemberRole{kb.ID: types.OrgRoleViewer}},
|
||||
tenantService: &stubTenantService{tenants: map[uint64]*types.Tenant{2: {ID: 2}}},
|
||||
resourceCatalog: catalog, storageResolver: storage,
|
||||
}
|
||||
ep := &types.MCPEndpoint{
|
||||
ID: "ep", TenantID: 1, KnowledgeBaseIDs: types.StringArray{kb.ID},
|
||||
Tools: types.StringArray{types.MCPEndpointToolReadDocument, types.MCPEndpointToolAsk},
|
||||
}
|
||||
ctx := context.WithValue(mcpCallContext(1, ep), types.TenantInfoContextKey, &types.Tenant{ID: 1})
|
||||
return &resourceURLFixture{
|
||||
srv: srv, ctx: ctx, ep: ep, db: db, ref: ref, path: path, files: files, storage: storage,
|
||||
}
|
||||
}
|
||||
|
||||
func (f *resourceURLFixture) rewrite(result *mcp.CallToolResult) *mcp.CallToolResult {
|
||||
return f.srv.rewriteResourceURLs(f.ctx, f.ep, result)
|
||||
}
|
||||
|
||||
func (f *resourceURLFixture) updateResource(t *testing.T, updates map[string]any) {
|
||||
t.Helper()
|
||||
require.NoError(t, f.db.Model(&types.StoredResource{}).
|
||||
Where("handle = ?", strings.TrimPrefix(f.ref, types.ResourceScheme)).Updates(updates).Error)
|
||||
}
|
||||
|
||||
func TestMCPResourceURLsRewriteTextAndTypedStructuredContent(t *testing.T) {
|
||||
f := newResourceURLFixture(t)
|
||||
typed := map[string]any{
|
||||
"large_integer": uint64(1152921504606846977),
|
||||
"chunks": []map[string]any{{"images": []map[string]string{{"url": f.ref}}}},
|
||||
"references": []askReference{{Images: []askImage{{URL: f.ref}}}},
|
||||
"wiki": struct {
|
||||
Content string `json:"content"`
|
||||
}{Content: ""},
|
||||
}
|
||||
original := mcp.NewToolResultStructured(typed, "")
|
||||
result := f.rewrite(original)
|
||||
text := result.Content[0].(mcp.TextContent).Text
|
||||
require.NotContains(t, text, "resource://")
|
||||
require.Contains(t, text, "https://weknora.example/prefix/r/")
|
||||
raw, err := json.Marshal(result.StructuredContent)
|
||||
require.NoError(t, err)
|
||||
require.NotContains(t, string(raw), "resource://")
|
||||
require.Contains(t, string(raw), `"large_integer":1152921504606846977`)
|
||||
url := strings.TrimSuffix(strings.TrimPrefix(text, ", ")")
|
||||
require.Equal(t, 3, strings.Count(string(raw), url))
|
||||
resource, err := f.srv.resourceCatalog.ResolveAccessGrant(f.ctx, strings.TrimPrefix(
|
||||
url, "https://weknora.example/prefix/r/",
|
||||
))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, uint64(2), resource.TenantID)
|
||||
var grants int64
|
||||
require.NoError(t, f.db.Model(&types.ResourceAccessGrant{}).Count(&grants).Error)
|
||||
require.EqualValues(t, 1, grants, "one response must reuse one URL across text and metadata")
|
||||
require.Contains(t, original.Content[0].(mcp.TextContent).Text, f.ref)
|
||||
raw, err = json.Marshal(original.StructuredContent)
|
||||
require.NoError(t, err)
|
||||
require.Contains(t, string(raw), f.ref, "persisted/shared source values must remain untouched")
|
||||
require.Equal(t, uint64(2), f.storage.tenant)
|
||||
}
|
||||
|
||||
func TestMCPResourceURLsRequireExistingPreviewPermission(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
setup func(*testing.T, *resourceURLFixture)
|
||||
}{
|
||||
{"outside endpoint", func(_ *testing.T, f *resourceURLFixture) {
|
||||
f.ep.KnowledgeBaseIDs = types.StringArray{"other-kb"}
|
||||
}},
|
||||
{"revoked share", func(_ *testing.T, f *resourceURLFixture) {
|
||||
f.srv.kbShareService = &stubKBShareService{}
|
||||
}},
|
||||
{"wrong resource tenant", func(t *testing.T, f *resourceURLFixture) {
|
||||
f.updateResource(t, map[string]any{"tenant_id": 3})
|
||||
}},
|
||||
{"wrong physical tenant", func(t *testing.T, f *resourceURLFixture) {
|
||||
f.updateResource(t, map[string]any{"physical_path": "local://3/exports/figure.png"})
|
||||
}},
|
||||
{"deleted resource", func(t *testing.T, f *resourceURLFixture) {
|
||||
require.NoError(t, f.srv.resourceCatalog.MarkDeleted(f.ctx, f.ref))
|
||||
}},
|
||||
{"deleted document", func(t *testing.T, f *resourceURLFixture) {
|
||||
require.NoError(t, f.db.Delete(&types.Knowledge{ID: "doc-1"}).Error)
|
||||
}},
|
||||
{"deleted KB", func(t *testing.T, f *resourceURLFixture) {
|
||||
require.NoError(t, f.db.Delete(&types.KnowledgeBase{ID: "kb-1"}).Error)
|
||||
}},
|
||||
{"original upload", func(t *testing.T, f *resourceURLFixture) {
|
||||
f.updateResource(t, map[string]any{"physical_path": "local://2/doc-1/original.png"})
|
||||
require.NoError(t, f.db.Model(&types.ResourceBinding{}).Where("owner_id = ?", "doc-1").
|
||||
Update("relation", types.ResourceRelationSourceFile).Error)
|
||||
}},
|
||||
{"historical text only", func(t *testing.T, f *resourceURLFixture) {
|
||||
require.NoError(t, f.db.Where("owner_id = ?", "doc-1").Delete(&types.ResourceBinding{}).Error)
|
||||
require.NoError(t, f.db.Create(&types.Chunk{
|
||||
ID: "chunk", TenantID: 2, KnowledgeID: "doc-1", KnowledgeBaseID: "kb-1",
|
||||
Content: "", ImageInfo: `[{"url":"` + f.ref + `"}]`,
|
||||
}).Error)
|
||||
}},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
f := newResourceURLFixture(t)
|
||||
tc.setup(t, f)
|
||||
result := f.rewrite(mcp.NewToolResultText(f.ref))
|
||||
require.Equal(t, f.ref, result.Content[0].(mcp.TextContent).Text)
|
||||
require.Zero(t, f.storage.calls)
|
||||
var count int64
|
||||
require.NoError(t, f.db.Model(&types.ResourceAccessGrant{}).Count(&count).Error)
|
||||
require.Zero(t, count, "denied references must never mint public grants")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMCPResourceURLsUnrestrictedEndpointCoversSharedKB(t *testing.T) {
|
||||
// ask on an unrestricted endpoint searches the agent's KBs, which can be
|
||||
// shared from another workspace; the caller's viewer grant is what counts.
|
||||
f := newResourceURLFixture(t)
|
||||
f.ep.KnowledgeBaseIDs = nil
|
||||
kbs := f.srv.kbService.(*stubKBService)
|
||||
for i := 0; i < 20; i++ {
|
||||
id := "own-" + strconv.Itoa(i)
|
||||
kbs.kbs[id] = &types.KnowledgeBase{ID: id, TenantID: 1}
|
||||
}
|
||||
result := f.rewrite(mcp.NewToolResultText(f.ref))
|
||||
require.True(t, strings.HasPrefix(result.Content[0].(mcp.TextContent).Text, "https://weknora.example/prefix/r/"))
|
||||
require.Equal(t, 1, kbs.lookups, "only KBs that bind the reference are authorized")
|
||||
|
||||
f = newResourceURLFixture(t)
|
||||
f.ep.KnowledgeBaseIDs = nil
|
||||
f.srv.kbShareService = &stubKBShareService{}
|
||||
result = f.rewrite(mcp.NewToolResultText(f.ref))
|
||||
require.Equal(t, f.ref, result.Content[0].(mcp.TextContent).Text)
|
||||
}
|
||||
|
||||
func TestMCPResourceURLsStructuredContentShapes(t *testing.T) {
|
||||
f := newResourceURLFixture(t)
|
||||
result := f.rewrite(mcp.NewToolResultStructured([]map[string]string{{"url": f.ref}}, "list"))
|
||||
raw, err := json.Marshal(result.StructuredContent)
|
||||
require.NoError(t, err)
|
||||
require.NotContains(t, string(raw), "resource://")
|
||||
require.Contains(t, string(raw), "https://weknora.example/prefix/r/")
|
||||
|
||||
type plain struct{ Count uint64 }
|
||||
result = f.rewrite(mcp.NewToolResultStructured(plain{Count: 7}, "no references"))
|
||||
require.Equal(t, plain{Count: 7}, result.StructuredContent, "no reference keeps the typed value")
|
||||
}
|
||||
|
||||
func TestMCPResourceURLsLegacyGlobalFallbackUsesOwner(t *testing.T) {
|
||||
f := newResourceURLFixture(t)
|
||||
t.Setenv("APP_EXTERNAL_URL", "")
|
||||
t.Setenv("STORAGE_TYPE", "minio")
|
||||
f.updateResource(t, map[string]any{"physical_path": "minio://bucket/2/exports/figure.png", "provider": "minio"})
|
||||
f.srv.storageResolver = service.NewStorageBackendService(
|
||||
repository.NewStorageBackendRepository(f.db), nil, f.srv.resourceCatalog,
|
||||
)
|
||||
f.srv.fileService = f.catalogWrapped()
|
||||
result := f.rewrite(mcp.NewToolResultText(f.ref))
|
||||
require.Equal(t, f.files.url, result.Content[0].(mcp.TextContent).Text)
|
||||
require.Equal(t, "minio://bucket/2/exports/figure.png", f.files.path)
|
||||
require.Equal(t, uint64(2), f.files.tenant)
|
||||
require.Equal(t, uint64(2), f.files.tenantInfo)
|
||||
}
|
||||
|
||||
func TestMCPResourceURLsLegacyPathsAndSafeFallback(t *testing.T) {
|
||||
f := newResourceURLFixture(t)
|
||||
t.Setenv("APP_EXTERNAL_URL", "")
|
||||
result := f.rewrite(mcp.NewToolResultText(f.path))
|
||||
require.Equal(t, f.files.url, result.Content[0].(mcp.TextContent).Text)
|
||||
f.files.url = f.path
|
||||
result = f.rewrite(mcp.NewToolResultText(f.ref))
|
||||
require.Equal(t, f.ref, result.Content[0].(mcp.TextContent).Text, "no public URL leaves reference intact")
|
||||
f.files.err = errors.New("storage unavailable")
|
||||
result = f.rewrite(mcp.NewToolResultText(f.ref))
|
||||
require.Equal(t, f.ref, result.Content[0].(mcp.TextContent).Text)
|
||||
f.storage.err = errors.New("backend unavailable")
|
||||
f.srv.fileService = f.catalogWrapped()
|
||||
f.updateResource(t, map[string]any{
|
||||
"storage_backend_id": "explicit", "physical_path": "storage://explicit/" + f.path,
|
||||
})
|
||||
before := f.files.calls
|
||||
result = f.rewrite(mcp.NewToolResultText(f.ref))
|
||||
require.Equal(t, f.ref, result.Content[0].(mcp.TextContent).Text)
|
||||
require.Equal(t, before, f.files.calls, "explicit backend must never fall back to another bucket")
|
||||
}
|
||||
|
||||
func TestMCPResourceURLsSkipErrorsAndPlainResults(t *testing.T) {
|
||||
f := newResourceURLFixture(t)
|
||||
failed := mcp.NewToolResultError(f.ref)
|
||||
require.Same(t, failed, f.rewrite(failed))
|
||||
require.Nil(t, f.rewrite(nil))
|
||||
plain := "unchanged https://example.com/public.png"
|
||||
require.Equal(t, plain, f.rewrite(mcp.NewToolResultText(plain)).Content[0].(mcp.TextContent).Text)
|
||||
require.Zero(t, f.storage.calls)
|
||||
}
|
||||
|
||||
func TestMCPExistingToolTransportRewritesResourceURLs(t *testing.T) {
|
||||
f := newResourceURLFixture(t)
|
||||
srv := NewServer(f.srv.kbService, nil, nil, nil, nil, nil, nil, f.srv.kbShareService,
|
||||
f.srv.tenantService, nil, nil, nil, nil, f.srv.resourceCatalog, nil, f.srv.storageResolver)
|
||||
// Replace the existing document handler to isolate the outbound middleware
|
||||
// while retaining the real MCP transport, catalog and endpoint guard.
|
||||
srv.mcp.AddTool(readDocumentTool(), func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
return mcp.NewToolResultStructured(map[string]any{"image": f.ref}, ""), nil
|
||||
})
|
||||
r := gin.New()
|
||||
r.POST("/mcp/:endpoint_id", func(c *gin.Context) {
|
||||
c.Request = c.Request.WithContext(f.ctx)
|
||||
c.Next()
|
||||
}, gin.WrapH(srv.Handler()))
|
||||
response := rpc(t, r, "tools/call", map[string]any{
|
||||
"name": types.MCPEndpointToolReadDocument, "arguments": map[string]any{"knowledge_id": "doc-1"},
|
||||
})
|
||||
raw, err := json.Marshal(response)
|
||||
require.NoError(t, err)
|
||||
require.NotContains(t, string(raw), "resource://")
|
||||
require.Contains(t, string(raw), "https://weknora.example/prefix/r/")
|
||||
require.NotContains(t, toolNames(t, rpc(t, r, "tools/list", map[string]any{})), "get_image")
|
||||
}
|
||||
|
|
@ -71,7 +71,7 @@ func (s *Server) resolveKB(
|
|||
func (s *Server) scopedKBContext(
|
||||
ctx context.Context, kb *types.KnowledgeBase, required types.OrgMemberRole,
|
||||
) (context.Context, error) {
|
||||
grant, err := s.resolveKB(ctx, kb, required)
|
||||
_, scoped, err := s.authorizeKB(ctx, kb, required)
|
||||
if err != nil {
|
||||
if errors.Is(err, access.ErrForbidden) || errors.Is(err, access.ErrUnauthorized) {
|
||||
if required == types.OrgRoleViewer {
|
||||
|
|
@ -81,16 +81,28 @@ func (s *Server) scopedKBContext(
|
|||
}
|
||||
return ctx, err
|
||||
}
|
||||
return scoped, nil
|
||||
}
|
||||
|
||||
// authorizeKB resolves the caller's grant on kb and returns it together with
|
||||
// the owner-scoped context described on scopedKBContext.
|
||||
func (s *Server) authorizeKB(
|
||||
ctx context.Context, kb *types.KnowledgeBase, required types.OrgMemberRole,
|
||||
) (*access.KBAccess, context.Context, error) {
|
||||
grant, err := s.resolveKB(ctx, kb, required)
|
||||
if err != nil {
|
||||
return nil, ctx, err
|
||||
}
|
||||
scoped := grant.Context(ctx)
|
||||
caller := types.CallerFromContext(ctx)
|
||||
if kb.TenantID != caller.TenantID && s.tenantService != nil {
|
||||
owner, err := s.tenantService.GetTenantByID(ctx, kb.TenantID)
|
||||
if err != nil || owner == nil {
|
||||
return ctx, fmt.Errorf("the workspace owning knowledge base %q is unavailable", kb.ID)
|
||||
return nil, ctx, fmt.Errorf("the workspace owning knowledge base %q is unavailable", kb.ID)
|
||||
}
|
||||
scoped = context.WithValue(scoped, types.TenantInfoContextKey, owner)
|
||||
}
|
||||
return scoped, nil
|
||||
return grant, scoped, nil
|
||||
}
|
||||
|
||||
// selectKnowledgeBases narrows the allowed set to the ones a caller named,
|
||||
|
|
|
|||
|
|
@ -13,10 +13,12 @@ import (
|
|||
|
||||
type stubKBService struct {
|
||||
interfaces.KnowledgeBaseService
|
||||
kbs map[string]*types.KnowledgeBase
|
||||
kbs map[string]*types.KnowledgeBase
|
||||
lookups int
|
||||
}
|
||||
|
||||
func (s *stubKBService) GetKnowledgeBaseByIDOnly(_ context.Context, id string) (*types.KnowledgeBase, error) {
|
||||
s.lookups++
|
||||
kb, ok := s.kbs[id]
|
||||
if !ok {
|
||||
return nil, errors.New("not found")
|
||||
|
|
|
|||
|
|
@ -51,6 +51,9 @@ type Server struct {
|
|||
agentService interfaces.CustomAgentService
|
||||
kbShareService interfaces.KBShareService
|
||||
tenantService interfaces.TenantService
|
||||
resourceCatalog interfaces.ResourceCatalog
|
||||
fileService interfaces.FileService
|
||||
storageResolver interfaces.StorageBackendResolver
|
||||
endpointRepo interfaces.MCPEndpointRepository
|
||||
db *gorm.DB
|
||||
cfg *config.Config
|
||||
|
|
@ -77,6 +80,9 @@ func NewServer(
|
|||
db *gorm.DB,
|
||||
cfg *config.Config,
|
||||
redisClient *redis.Client,
|
||||
resourceCatalog interfaces.ResourceCatalog,
|
||||
fileService interfaces.FileService,
|
||||
storageResolver interfaces.StorageBackendResolver,
|
||||
) *Server {
|
||||
s := &Server{
|
||||
kbService: kbService,
|
||||
|
|
@ -91,6 +97,9 @@ func NewServer(
|
|||
endpointRepo: endpointRepo,
|
||||
db: db,
|
||||
cfg: cfg,
|
||||
resourceCatalog: resourceCatalog,
|
||||
fileService: fileService,
|
||||
storageResolver: storageResolver,
|
||||
limiter: ratelimit.New(redisClient, rateLimitKeyPrefix, time.Minute, ""),
|
||||
}
|
||||
// The local fallback map only grows without periodic eviction; the server
|
||||
|
|
@ -164,7 +173,11 @@ func (s *Server) guardTool(next server.ToolHandlerFunc) server.ToolHandlerFunc {
|
|||
return mcp.NewToolResultError("rate limit exceeded for this endpoint, retry shortly"), nil
|
||||
}
|
||||
s.touchLastUsed(ctx, ep.ID)
|
||||
return next(ctx, req)
|
||||
result, err := next(ctx, req)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
return s.rewriteResourceURLs(ctx, ep, result), nil
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -44,7 +44,7 @@ func newTestEngineWithRepo(t *testing.T, ep *types.MCPEndpoint) (*gin.Engine, *r
|
|||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
repo := &recordingEndpointRepo{touched: make(chan string, 8)}
|
||||
srv := NewServer(nil, nil, nil, nil, nil, nil, nil, nil, nil, repo, nil, nil, nil)
|
||||
srv := NewServer(nil, nil, nil, nil, nil, nil, nil, nil, nil, repo, nil, nil, nil, nil, nil, nil)
|
||||
r := gin.New()
|
||||
inject := func(c *gin.Context) {
|
||||
if ep != nil {
|
||||
|
|
|
|||
|
|
@ -2,7 +2,9 @@ package mcpserver
|
|||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
|
@ -41,11 +43,20 @@ func askTool() mcp.Tool {
|
|||
}
|
||||
|
||||
type askReference struct {
|
||||
KnowledgeID string `json:"knowledge_id"`
|
||||
KnowledgeTitle string `json:"knowledge_title,omitempty"`
|
||||
ChunkID string `json:"chunk_id"`
|
||||
Score float64 `json:"score,omitempty"`
|
||||
Excerpt string `json:"excerpt"`
|
||||
KnowledgeID string `json:"knowledge_id"`
|
||||
KnowledgeTitle string `json:"knowledge_title,omitempty"`
|
||||
ChunkID string `json:"chunk_id"`
|
||||
Score float64 `json:"score,omitempty"`
|
||||
Excerpt string `json:"excerpt"`
|
||||
Images []askImage `json:"images,omitempty"`
|
||||
}
|
||||
|
||||
// Keep image references separate from the truncated excerpt. OriginalURL is
|
||||
// parser provenance, not a serving URL, and must not be exposed as a fallback.
|
||||
type askImage struct {
|
||||
URL string `json:"url"`
|
||||
Caption string `json:"caption,omitempty"`
|
||||
OCRText string `json:"ocr_text,omitempty"`
|
||||
}
|
||||
|
||||
func (s *Server) handleAsk(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
|
|
@ -93,6 +104,11 @@ func (s *Server) handleAsk(ctx context.Context, req mcp.CallToolRequest) (*mcp.C
|
|||
title = r.KnowledgeID
|
||||
}
|
||||
fmt.Fprintf(&b, "[%d] %s (document %s)\n", i+1, title, r.KnowledgeID)
|
||||
for _, img := range r.Images {
|
||||
// Preserve image references for text-only MCP hosts as well.
|
||||
// strconv.Quote, unlike json.Marshal, keeps & < > literal.
|
||||
fmt.Fprintf(&b, " Image: %s\n", strconv.Quote(img.URL))
|
||||
}
|
||||
}
|
||||
fmt.Fprintf(&b, "\nsession_id: %s", session.ID)
|
||||
text = b.String()
|
||||
|
|
@ -400,7 +416,7 @@ const askExcerptMaxRunes = 300
|
|||
|
||||
func summarizeReferences(refs []*types.SearchResult) []askReference {
|
||||
out := make([]askReference, 0, len(refs))
|
||||
seen := map[string]struct{}{}
|
||||
seen := map[string]int{}
|
||||
for _, r := range refs {
|
||||
if r == nil {
|
||||
continue
|
||||
|
|
@ -409,21 +425,69 @@ func summarizeReferences(refs []*types.SearchResult) []askReference {
|
|||
if key == "" {
|
||||
key = r.KnowledgeID + ":" + fmt.Sprint(r.ChunkIndex)
|
||||
}
|
||||
if _, dup := seen[key]; dup {
|
||||
if index, dup := seen[key]; dup {
|
||||
out[index].Images = summarizeReferenceImages(r.ImageInfo, out[index].Images)
|
||||
continue
|
||||
}
|
||||
seen[key] = struct{}{}
|
||||
excerpt := strings.TrimSpace(r.Content)
|
||||
if runes := []rune(excerpt); len(runes) > askExcerptMaxRunes {
|
||||
excerpt = string(runes[:askExcerptMaxRunes]) + "…"
|
||||
}
|
||||
seen[key] = len(out)
|
||||
out = append(out, askReference{
|
||||
KnowledgeID: r.KnowledgeID,
|
||||
KnowledgeTitle: r.KnowledgeTitle,
|
||||
ChunkID: r.ID,
|
||||
Score: r.Score,
|
||||
Excerpt: excerpt,
|
||||
Excerpt: truncateExcerpt(strings.TrimSpace(r.Content)),
|
||||
Images: summarizeReferenceImages(r.ImageInfo, nil),
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// truncateExcerpt cuts at askExcerptMaxRunes but never inside a storage
|
||||
// reference: half a handle is unusable and would only cost a failed lookup.
|
||||
// Whole image references are kept in askReference.Images instead.
|
||||
func truncateExcerpt(excerpt string) string {
|
||||
runes := []rune(excerpt)
|
||||
if len(runes) <= askExcerptMaxRunes {
|
||||
return excerpt
|
||||
}
|
||||
cut := len(string(runes[:askExcerptMaxRunes]))
|
||||
for _, loc := range types.StorageReferencePattern.FindAllStringIndex(excerpt, -1) {
|
||||
if loc[0] >= cut {
|
||||
break
|
||||
}
|
||||
if cut < loc[1] {
|
||||
cut = loc[0]
|
||||
break
|
||||
}
|
||||
}
|
||||
return excerpt[:cut] + "…"
|
||||
}
|
||||
|
||||
func summarizeReferenceImages(raw string, out []askImage) []askImage {
|
||||
var infos []types.ImageInfo
|
||||
if err := json.Unmarshal([]byte(raw), &infos); err != nil {
|
||||
return out
|
||||
}
|
||||
seen := make(map[string]int, len(out)+len(infos))
|
||||
for i, img := range out {
|
||||
seen[img.URL] = i
|
||||
}
|
||||
for _, info := range infos {
|
||||
url := strings.TrimSpace(info.URL)
|
||||
if url == "" {
|
||||
continue
|
||||
}
|
||||
if index, dup := seen[url]; dup {
|
||||
if out[index].Caption == "" {
|
||||
out[index].Caption = info.Caption
|
||||
}
|
||||
if out[index].OCRText == "" {
|
||||
out[index].OCRText = info.OCRText
|
||||
}
|
||||
continue
|
||||
}
|
||||
seen[url] = len(out)
|
||||
out = append(out, askImage{URL: url, Caption: info.Caption, OCRText: info.OCRText})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,117 @@
|
|||
package mcpserver
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/event"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/mark3labs/mcp-go/mcp"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestSummarizeReferencesPreservesImagesOutsideExcerpt(t *testing.T) {
|
||||
const ref = "resource://AbCdEfGhIjKlMnOpQrStUv"
|
||||
refs := summarizeReferences([]*types.SearchResult{
|
||||
nil,
|
||||
{
|
||||
ID: "chunk", KnowledgeID: "doc", Content: strings.Repeat("长", 400),
|
||||
ImageInfo: `[{"url":"` + ref + `","caption":"diagram","original_url":"private-source"},` +
|
||||
`{"url":"","original_url":"private-only"}]`,
|
||||
},
|
||||
{ID: "chunk", KnowledgeID: "doc", ImageInfo: `[{"url":"` + ref + `","ocr_text":"details"}]`},
|
||||
{ID: "broken", ImageInfo: `malformed`},
|
||||
})
|
||||
require.Len(t, refs, 2)
|
||||
require.Equal(t, strings.Repeat("长", askExcerptMaxRunes)+"…", refs[0].Excerpt)
|
||||
require.Equal(t, []askImage{{URL: ref, Caption: "diagram", OCRText: "details"}}, refs[0].Images)
|
||||
require.Empty(t, refs[1].Images)
|
||||
|
||||
cut := summarizeReferences([]*types.SearchResult{{
|
||||
ID: "cut", Content: strings.Repeat("x", askExcerptMaxRunes-10) + "",
|
||||
}})
|
||||
require.Equal(t, strings.Repeat("x", askExcerptMaxRunes-10)+"
|
||||
raw, err := json.Marshal(refs)
|
||||
require.NoError(t, err)
|
||||
require.NotContains(t, string(raw), "private-source")
|
||||
require.NotContains(t, string(raw), "private-only")
|
||||
}
|
||||
|
||||
type imageAskSessionService struct {
|
||||
interfaces.SessionService
|
||||
refs []*types.SearchResult
|
||||
}
|
||||
|
||||
func (s *imageAskSessionService) CreateSession(_ context.Context, session *types.Session) (*types.Session, error) {
|
||||
session.ID = "session-1"
|
||||
return session, nil
|
||||
}
|
||||
|
||||
func (s *imageAskSessionService) SetSessionOwnerID(context.Context, uint64, string, string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *imageAskSessionService) KnowledgeQA(ctx context.Context, _ *types.QARequest, bus *event.EventBus) error {
|
||||
if err := bus.EmitAndWait(ctx, event.Event{
|
||||
Type: event.EventAgentReferences, Data: event.AgentReferencesData{References: s.refs},
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
return bus.EmitAndWait(ctx, event.Event{
|
||||
Type: event.EventAgentFinalAnswer,
|
||||
Data: event.AgentFinalAnswerData{Content: "A textual answer without a Markdown image.", Done: true},
|
||||
})
|
||||
}
|
||||
|
||||
type imageAskMessageService struct{ interfaces.MessageService }
|
||||
|
||||
func (s *imageAskMessageService) CreateMessage(_ context.Context, message *types.Message) (*types.Message, error) {
|
||||
message.ID = "message-" + message.Role
|
||||
return message, nil
|
||||
}
|
||||
|
||||
func (s *imageAskMessageService) UpdateMessage(context.Context, *types.Message) error { return nil }
|
||||
|
||||
func TestAskExposesImageHandlesToTextAndStructuredClients(t *testing.T) {
|
||||
f := newResourceURLFixture(t)
|
||||
const publicURL = "https://cdn.example/img.png?a=1&b=2"
|
||||
info, err := json.Marshal([]types.ImageInfo{{
|
||||
URL: f.ref, Caption: "chart", OCRText: "values", OriginalURL: "private-parser-locator",
|
||||
}, {URL: publicURL}})
|
||||
require.NoError(t, err)
|
||||
f.srv.sessionService = &imageAskSessionService{refs: []*types.SearchResult{{
|
||||
ID: "chunk", KnowledgeID: "doc-1", Content: strings.Repeat("long text ", 100), ImageInfo: string(info),
|
||||
}}}
|
||||
f.srv.messageService = &imageAskMessageService{}
|
||||
f.srv.agentService = &stubAgentService{agents: map[string]*types.CustomAgent{
|
||||
types.BuiltinQuickAnswerID: {ID: types.BuiltinQuickAnswerID, IsBuiltin: true},
|
||||
}}
|
||||
result, err := f.srv.handleAsk(f.ctx, mcp.CallToolRequest{Params: mcp.CallToolParams{
|
||||
Arguments: map[string]any{"question": "Explain the diagram"},
|
||||
}})
|
||||
require.NoError(t, err)
|
||||
require.False(t, result.IsError, "%#v", result.Content)
|
||||
require.Contains(t, result.Content[0].(mcp.TextContent).Text, `Image: "`+f.ref+`"`)
|
||||
require.Contains(t, result.Content[0].(mcp.TextContent).Text, `Image: "`+publicURL+`"`)
|
||||
result = f.rewrite(result)
|
||||
raw, err := json.Marshal(result.StructuredContent)
|
||||
require.NoError(t, err)
|
||||
var parsed struct {
|
||||
References []askReference `json:"references"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(raw, &parsed))
|
||||
require.Len(t, parsed.References, 1)
|
||||
require.Len(t, parsed.References[0].Images, 2)
|
||||
require.Equal(t, publicURL, parsed.References[0].Images[1].URL)
|
||||
img := parsed.References[0].Images[0]
|
||||
require.True(t, strings.HasPrefix(img.URL, "https://weknora.example/prefix/r/"))
|
||||
require.Equal(t, "chart", img.Caption)
|
||||
require.Equal(t, "values", img.OCRText)
|
||||
require.Contains(t, result.Content[0].(mcp.TextContent).Text, img.URL)
|
||||
require.NotContains(t, string(raw), "private-parser-locator")
|
||||
require.NotContains(t, string(raw), "resource://")
|
||||
}
|
||||
|
|
@ -49,7 +49,7 @@ type stubMCPEndpointServiceForRoutes struct {
|
|||
func TestMCPServerRoutesAreMountedAndReported(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
engine := gin.New()
|
||||
srv := mcpserver.NewServer(nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
|
||||
srv := mcpserver.NewServer(nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
|
||||
RegisterMCPServerRoutes(engine, srv, &stubMCPEndpointServiceForRoutes{}, nil)
|
||||
|
||||
routes := map[string]bool{}
|
||||
|
|
|
|||
|
|
@ -122,6 +122,16 @@ func (w *Rewriter) CopyData(ctx context.Context, data map[string]interface{}) ma
|
|||
return out
|
||||
}
|
||||
|
||||
// CopyValue is CopyData for a decoded JSON value of any shape (object, array
|
||||
// or scalar). Unchanged values are returned as-is.
|
||||
func (w *Rewriter) CopyValue(ctx context.Context, value interface{}) interface{} {
|
||||
if !w.Enabled() {
|
||||
return value
|
||||
}
|
||||
rewritten, _ := w.copyValue(ctx, value, 0)
|
||||
return rewritten
|
||||
}
|
||||
|
||||
// maxDataDepth bounds recursion into tool-defined metadata. Renderable content
|
||||
// sits within a couple of levels; the cap only guards against a pathologically
|
||||
// nested payload.
|
||||
|
|
|
|||
|
|
@ -49,6 +49,12 @@ MCP 用于智能体与外部工具之间的连接。WeKnora 支持接入外部 M
|
|||
| Wiki | `wiki_search`、`wiki_read_page`、`wiki_index` | 只对开启了 Wiki 的知识库生效;`wiki_search` 的 `query` 保持原有的正则语义(大小写不敏感),不是合法正则的文本按字面匹配;`regex=false` 强制字面匹配,`regex=true` 要求合法正则 |
|
||||
| 写入 | `add_document`、`update_document`、`delete_document` | 默认关闭;支持 Markdown 文本或 URL 导入 |
|
||||
|
||||
现有 MCP 工具的返回结果会复用 REST/IM 的资源链接转换:正文、Wiki 内容以及结构化数据中的图片引用,都会在权限校验后转换为可直接访问的 HTTP(S) 链接,不需要新增工具或修改端点工具清单。`ask` 的 `references[].images` 保留图片 URL、caption 和 OCR 文本,文本引用列表也包含图片链接,避免正文摘要截断后丢失图片信息。
|
||||
|
||||
本地或私有存储请配置外部客户端可访问的 `APP_EXTERNAL_URL`,并确保反向代理转发 `/r/`。`resource://` 图片沿用有时效的 `/r/<token>` 链接;其他存储地址使用对应存储服务生成的 HTTP(S) URL。一次工具调用中同一资源只转换一次,返回链接不写回文档或会话记录。无法生成可访问链接时保留原引用,不中断文本结果。
|
||||
|
||||
生成链接前会重新检查端点知识库范围、共享权限、资源所属空间和有效文档绑定,沿用知识库图片预览的权限规则;未限定知识库的端点按调用者可查看的知识库判断,因此 `ask` 通过智能体检索到的共享知识库图片同样可以转换;原始上传文件不会因为出现在结果文本中就获得下载链接。已有绑定的历史存储路径可以转换。对于缺少图片绑定的历史文档,需要由有权限的管理员重新解析文档,完成后重新检索;不能仅凭可编辑的正文或 `image_info` 自动补授文件权限。
|
||||
|
||||
> **`grep_chunks` 的召回有上限。** 它基于索引取候选,每次最多 30 条,再用正则筛选,所以返回的每条都匹配模式,但不保证穷尽:库里存在的匹配也可能没进候选池。容易漏的情况有三类:`foo.*bar` 这类组合模式,候选按 foo、bar 的相关度排序,真正相邻出现的分块可能排不进前 30;`C++` 这类几乎只剩符号的模式,抽出的字面词只有 `C`,在索引里几乎没有区分度;没有关键词索引的库改用语义索引取候选,字面匹配更依赖运气。旧实现对 chunks 表做全表正则扫描,能保证"有就能找到",但数据量大时代价过高,已经移除。需要在某篇文档里穷尽查找时,用 `read_document` 的 `query`,它会顺序扫完整篇文档。
|
||||
|
||||
工具实现直接复用 Agent 的原生工具(`internal/agent/tools/`),鉴权复用 API Key 的作用域模型:端点被换算成一把仅含 retrieve / chat / ingest 等能力、限定知识库范围的作用域,所以后端各服务对它的检查与对受限 API Key 完全一致。实现细节见下方内置 MCP Server 参考。
|
||||
|
|
|
|||
Loading…
Reference in New Issue