chore: 初始化仓库,导入项目基线代码
Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、 Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。 今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
commit
7ec21f35b0
5767 files changed
+1436788
No files matched your search
@@ -0,0 +1,50 @@
|
||||
package mcpserver
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestGrepPatternAndTermsKeepsRegexSemantics(t *testing.T) {
|
||||
cases := []struct {
|
||||
query string
|
||||
terms string
|
||||
matches []string
|
||||
rejects []string
|
||||
}{
|
||||
{
|
||||
query: "stardust|skyvault", terms: "stardust skyvault",
|
||||
matches: []string{"the Stardust drive", "SKYVAULT"}, rejects: []string{"star dust"},
|
||||
},
|
||||
{
|
||||
query: `\bE1001\b`, terms: "E1001",
|
||||
matches: []string{"code E1001 raised"}, rejects: []string{"E10012"},
|
||||
},
|
||||
{
|
||||
query: "psionic.*engine", terms: "psionic engine",
|
||||
matches: []string{"psionic warp engine"}, rejects: []string{"engine psionic"},
|
||||
},
|
||||
{
|
||||
// Not a valid expression: matched literally, as it used to fail.
|
||||
query: "C++", terms: "C",
|
||||
matches: []string{"written in C++"}, rejects: []string{"written in C"},
|
||||
},
|
||||
{query: "图片素材", terms: "图片素材", matches: []string{"关于图片素材的说明"}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
re, terms := grepPatternAndTerms(tc.query)
|
||||
if terms != tc.terms {
|
||||
t.Errorf("%q terms = %q, want %q", tc.query, terms, tc.terms)
|
||||
}
|
||||
for _, s := range tc.matches {
|
||||
if !re.MatchString(s) {
|
||||
t.Errorf("%q should match %q", tc.query, s)
|
||||
}
|
||||
}
|
||||
for _, s := range tc.rejects {
|
||||
if re.MatchString(s) {
|
||||
t.Errorf("%q should not match %q", tc.query, s)
|
||||
}
|
||||
}
|
||||
}
|
||||
if _, terms := grepPatternAndTerms(`^\d+$`); terms != "" {
|
||||
t.Fatalf("a pattern without literal text has no index terms, got %q", terms)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
package mcpserver
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"academy/internal/application/access"
|
||||
filesvc "academy/internal/application/service/file"
|
||||
"academy/internal/logger"
|
||||
"academy/internal/storageurl"
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
secutils "academy/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"
|
||||
|
||||
"academy/internal/application/repository"
|
||||
"academy/internal/application/service"
|
||||
filesvc "academy/internal/application/service/file"
|
||||
"academy/internal/types"
|
||||
"academy/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://academy.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://academy.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://academy.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://academy.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://academy.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://academy.example/prefix/r/")
|
||||
require.NotContains(t, toolNames(t, rpc(t, r, "tools/list", map[string]any{})), "get_image")
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
package mcpserver
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"academy/internal/agent/tools"
|
||||
"academy/internal/application/access"
|
||||
"academy/internal/logger"
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
// allowedKnowledgeBases returns every knowledge base the endpoint may touch,
|
||||
// each one re-authorized for the calling principal through access.ResolveKB
|
||||
// so a stale or foreign ID in the allowlist is dropped rather than trusted.
|
||||
// An unrestricted endpoint sees the workspace's own knowledge bases.
|
||||
func (s *Server) allowedKnowledgeBases(ctx context.Context, ep *types.MCPEndpoint) ([]*types.KnowledgeBase, error) {
|
||||
if !ep.RestrictsKnowledgeBases() {
|
||||
return s.kbService.ListKnowledgeBases(ctx)
|
||||
}
|
||||
out := make([]*types.KnowledgeBase, 0, len(ep.KnowledgeBaseIDs))
|
||||
for _, id := range ep.KnowledgeBaseIDs {
|
||||
kb, err := s.authorizedKnowledgeBase(ctx, id, types.OrgRoleViewer)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "[mcpserver] endpoint %s references unavailable knowledge base %s: %v",
|
||||
ep.ID, id, err)
|
||||
continue
|
||||
}
|
||||
out = append(out, kb)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// authorizedKnowledgeBase loads a knowledge base by ID and resolves the
|
||||
// caller's permission on it (ownership or organization share). The returned
|
||||
// error is access.ErrForbidden / ErrNotFound for authorization failures.
|
||||
func (s *Server) authorizedKnowledgeBase(
|
||||
ctx context.Context, kbID string, required types.OrgMemberRole,
|
||||
) (*types.KnowledgeBase, error) {
|
||||
kb, err := s.kbService.GetKnowledgeBaseByIDOnly(ctx, strings.TrimSpace(kbID))
|
||||
if err != nil || kb == nil {
|
||||
return nil, access.ErrNotFound
|
||||
}
|
||||
if _, err := s.resolveKB(ctx, kb, required); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return kb, nil
|
||||
}
|
||||
|
||||
func (s *Server) resolveKB(
|
||||
ctx context.Context, kb *types.KnowledgeBase, required types.OrgMemberRole,
|
||||
) (*access.KBAccess, error) {
|
||||
request := access.KBRequest{Caller: types.CallerFromContext(ctx)}
|
||||
return access.ResolveKB(ctx, request, kb, required, s.kbShareService, nil)
|
||||
}
|
||||
|
||||
// scopedKBContext authorizes one knowledge base at the required permission
|
||||
// and returns the context every document-level call must run under: it
|
||||
// carries the resolved grant (so access.RequireKBWrite sees an explicit
|
||||
// authorization instead of an implicit "same tenant") and switches the
|
||||
// execution tenant to the knowledge base owner, which is what makes shared
|
||||
// knowledge bases work. Their documents are stored under the owner tenant,
|
||||
// so listing, reading and writing them through the caller's tenant would
|
||||
// either find nothing or create rows under the wrong tenant.
|
||||
//
|
||||
// TenantInfo is swapped to the owner as well so model and storage settings
|
||||
// resolve against the workspace that holds the data, mirroring the service
|
||||
// layer's withKBWriteTenantInfo.
|
||||
func (s *Server) scopedKBContext(
|
||||
ctx context.Context, kb *types.KnowledgeBase, required types.OrgMemberRole,
|
||||
) (context.Context, error) {
|
||||
_, 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 {
|
||||
return ctx, fmt.Errorf("this endpoint is not allowed to read knowledge base %q", kb.ID)
|
||||
}
|
||||
return ctx, fmt.Errorf("this endpoint is not allowed to write to knowledge base %q", kb.ID)
|
||||
}
|
||||
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 nil, ctx, fmt.Errorf("the workspace owning knowledge base %q is unavailable", kb.ID)
|
||||
}
|
||||
scoped = context.WithValue(scoped, types.TenantInfoContextKey, owner)
|
||||
}
|
||||
return grant, scoped, nil
|
||||
}
|
||||
|
||||
// selectKnowledgeBases narrows the allowed set to the ones a caller named,
|
||||
// accepting either IDs or exact (case-insensitive) names. With no selector
|
||||
// every allowed knowledge base is returned.
|
||||
func (s *Server) selectKnowledgeBases(
|
||||
ctx context.Context, ep *types.MCPEndpoint, requested []string,
|
||||
) ([]*types.KnowledgeBase, error) {
|
||||
allowed, err := s.allowedKnowledgeBases(ctx, ep)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(allowed) == 0 {
|
||||
return nil, fmt.Errorf("no knowledge base is available on this endpoint")
|
||||
}
|
||||
cleaned := make([]string, 0, len(requested))
|
||||
for _, r := range requested {
|
||||
if r = strings.TrimSpace(r); r != "" {
|
||||
cleaned = append(cleaned, r)
|
||||
}
|
||||
}
|
||||
if len(cleaned) == 0 {
|
||||
return allowed, nil
|
||||
}
|
||||
out := make([]*types.KnowledgeBase, 0, len(cleaned))
|
||||
seen := map[string]struct{}{}
|
||||
for _, sel := range cleaned {
|
||||
kb := matchKnowledgeBase(allowed, sel)
|
||||
if kb == nil {
|
||||
return nil, fmt.Errorf("knowledge base %q was not found or is outside this endpoint's scope; "+
|
||||
"call list_knowledge_bases to see what is available", sel)
|
||||
}
|
||||
if _, dup := seen[kb.ID]; dup {
|
||||
continue
|
||||
}
|
||||
seen[kb.ID] = struct{}{}
|
||||
out = append(out, kb)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func matchKnowledgeBase(kbs []*types.KnowledgeBase, selector string) *types.KnowledgeBase {
|
||||
for _, kb := range kbs {
|
||||
if kb.ID == selector {
|
||||
return kb
|
||||
}
|
||||
}
|
||||
for _, kb := range kbs {
|
||||
if strings.EqualFold(strings.TrimSpace(kb.Name), selector) {
|
||||
return kb
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// searchTargetsFor builds whole-knowledge-base search targets. TenantID is
|
||||
// carried per target because shared knowledge bases index under their owner.
|
||||
func searchTargetsFor(kbs []*types.KnowledgeBase) types.SearchTargets {
|
||||
targets := make(types.SearchTargets, 0, len(kbs))
|
||||
for _, kb := range kbs {
|
||||
targets = append(targets, &types.SearchTarget{
|
||||
Type: types.SearchTargetTypeKnowledgeBase,
|
||||
KnowledgeBaseID: kb.ID,
|
||||
TenantID: kb.TenantID,
|
||||
})
|
||||
}
|
||||
return targets
|
||||
}
|
||||
|
||||
func knowledgeBaseIDs(kbs []*types.KnowledgeBase) []string {
|
||||
ids := make([]string, 0, len(kbs))
|
||||
for _, kb := range kbs {
|
||||
ids = append(ids, kb.ID)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
// retrievableKnowledgeBases keeps knowledge bases that have a vector or
|
||||
// keyword index, i.e. the ones the search tools can actually query.
|
||||
func retrievableKnowledgeBases(kbs []*types.KnowledgeBase) []*types.KnowledgeBase {
|
||||
out := make([]*types.KnowledgeBase, 0, len(kbs))
|
||||
for _, kb := range kbs {
|
||||
if kb.IsVectorEnabled() || kb.IsKeywordEnabled() {
|
||||
out = append(out, kb)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// wikiKnowledgeBases keeps knowledge bases with a generated wiki.
|
||||
func wikiKnowledgeBases(kbs []*types.KnowledgeBase) []*types.KnowledgeBase {
|
||||
out := make([]*types.KnowledgeBase, 0, len(kbs))
|
||||
for _, kb := range kbs {
|
||||
if kb.IsWikiEnabled() {
|
||||
out = append(out, kb)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func wikiScopesFor(kbs []*types.KnowledgeBase) []tools.WikiScope {
|
||||
return tools.NewWikiScopesFromKBIDs(knowledgeBaseIDs(kbs))
|
||||
}
|
||||
|
||||
// knowledgeInScope loads a document and confirms it belongs to a knowledge
|
||||
// base the endpoint may touch. The lookup is tenant-agnostic because a shared
|
||||
// knowledge base's documents live under the owner tenant; the document must
|
||||
// then match an allowed knowledge base and that knowledge base's tenant.
|
||||
func (s *Server) knowledgeInScope(
|
||||
ctx context.Context, ep *types.MCPEndpoint, knowledgeID string,
|
||||
) (*types.Knowledge, *types.KnowledgeBase, error) {
|
||||
knowledgeID = strings.TrimSpace(knowledgeID)
|
||||
if knowledgeID == "" {
|
||||
return nil, nil, fmt.Errorf("knowledge_id is required")
|
||||
}
|
||||
k, err := s.knowledgeService.GetKnowledgeByIDOnly(ctx, knowledgeID)
|
||||
if err != nil || k == nil {
|
||||
return nil, nil, fmt.Errorf("document %q was not found", knowledgeID)
|
||||
}
|
||||
allowed, err := s.allowedKnowledgeBases(ctx, ep)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
kb := matchKnowledgeBase(allowed, k.KnowledgeBaseID)
|
||||
if kb == nil || kb.TenantID != k.TenantID {
|
||||
return nil, nil, fmt.Errorf("document %q is outside this endpoint's scope", knowledgeID)
|
||||
}
|
||||
return k, kb, nil
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
package mcpserver
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"academy/internal/application/access"
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
)
|
||||
|
||||
type stubKBService struct {
|
||||
interfaces.KnowledgeBaseService
|
||||
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")
|
||||
}
|
||||
return kb, nil
|
||||
}
|
||||
|
||||
func (s *stubKBService) ListKnowledgeBases(ctx context.Context) ([]*types.KnowledgeBase, error) {
|
||||
tenantID := types.MustTenantIDFromContext(ctx)
|
||||
out := []*types.KnowledgeBase{}
|
||||
for _, kb := range s.kbs {
|
||||
if kb.TenantID == tenantID {
|
||||
out = append(out, kb)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
type stubAgentService struct {
|
||||
interfaces.CustomAgentService
|
||||
agents map[string]*types.CustomAgent
|
||||
}
|
||||
|
||||
func (s *stubAgentService) GetAgentByID(_ context.Context, id string) (*types.CustomAgent, error) {
|
||||
agent, ok := s.agents[id]
|
||||
if !ok {
|
||||
return nil, errors.New("not found")
|
||||
}
|
||||
return agent, nil
|
||||
}
|
||||
|
||||
func mcpCallContext(tenantID uint64, ep *types.MCPEndpoint) context.Context {
|
||||
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, tenantID)
|
||||
ctx = context.WithValue(ctx, types.MCPEndpointContextKey, ep)
|
||||
ctx = types.WithTenantAPIKeyScope(ctx, types.MCPEndpointScope(ep))
|
||||
return types.WithCaller(ctx, types.Caller{TenantID: tenantID, UserID: "mcp-" + ep.ID, Role: types.TenantRoleViewer})
|
||||
}
|
||||
|
||||
func newScopeTestServer(kbs ...*types.KnowledgeBase) *Server {
|
||||
stub := &stubKBService{kbs: map[string]*types.KnowledgeBase{}}
|
||||
for _, kb := range kbs {
|
||||
stub.kbs[kb.ID] = kb
|
||||
}
|
||||
return &Server{kbService: stub}
|
||||
}
|
||||
|
||||
func TestAllowedKnowledgeBasesDropsForeignIDs(t *testing.T) {
|
||||
srv := newScopeTestServer(
|
||||
&types.KnowledgeBase{ID: "kb-own", TenantID: 1, Name: "Own"},
|
||||
&types.KnowledgeBase{ID: "kb-foreign", TenantID: 2, Name: "Foreign"},
|
||||
)
|
||||
ep := &types.MCPEndpoint{
|
||||
ID: "ep", TenantID: 1, KnowledgeBaseIDs: types.StringArray{"kb-own", "kb-foreign", "kb-gone"},
|
||||
}
|
||||
kbs, err := srv.allowedKnowledgeBases(mcpCallContext(1, ep), ep)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(kbs) != 1 || kbs[0].ID != "kb-own" {
|
||||
t.Fatalf("expected only the owned knowledge base, got %v", knowledgeBaseIDs(kbs))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSelectKnowledgeBasesMatchesIDOrName(t *testing.T) {
|
||||
srv := newScopeTestServer(
|
||||
&types.KnowledgeBase{ID: "kb-1", TenantID: 1, Name: "Product Docs"},
|
||||
&types.KnowledgeBase{ID: "kb-2", TenantID: 1, Name: "Support"},
|
||||
&types.KnowledgeBase{ID: "kb-3", TenantID: 2, Name: "Other tenant"},
|
||||
)
|
||||
ep := &types.MCPEndpoint{ID: "ep", TenantID: 1}
|
||||
ctx := mcpCallContext(1, ep)
|
||||
|
||||
all, err := srv.selectKnowledgeBases(ctx, ep, nil)
|
||||
if err != nil || len(all) != 2 {
|
||||
t.Fatalf("unrestricted endpoint must see its workspace only: %v %v", knowledgeBaseIDs(all), err)
|
||||
}
|
||||
picked, err := srv.selectKnowledgeBases(ctx, ep, []string{"product docs", "kb-2", "kb-2"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := knowledgeBaseIDs(picked); len(got) != 2 || got[0] != "kb-1" || got[1] != "kb-2" {
|
||||
t.Fatalf("name/id selection = %v", got)
|
||||
}
|
||||
_, err = srv.selectKnowledgeBases(ctx, ep, []string{"kb-3"})
|
||||
if err == nil || !strings.Contains(err.Error(), "outside") {
|
||||
t.Fatalf("foreign knowledge base must be rejected, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
type stubKBShareService struct {
|
||||
interfaces.KBShareService
|
||||
shared map[string]types.OrgMemberRole // kb id -> permission granted to any caller
|
||||
}
|
||||
|
||||
func (s *stubKBShareService) CheckTenantKBPermission(
|
||||
_ context.Context, kbID string, _ uint64, _ types.TenantRole,
|
||||
) (types.OrgMemberRole, bool, error) {
|
||||
perm, ok := s.shared[kbID]
|
||||
return perm, ok, nil
|
||||
}
|
||||
|
||||
type stubTenantService struct {
|
||||
interfaces.TenantService
|
||||
tenants map[uint64]*types.Tenant
|
||||
}
|
||||
|
||||
func (s *stubTenantService) GetTenantByID(_ context.Context, id uint64) (*types.Tenant, error) {
|
||||
t, ok := s.tenants[id]
|
||||
if !ok {
|
||||
return nil, errors.New("not found")
|
||||
}
|
||||
return t, nil
|
||||
}
|
||||
|
||||
type stubKnowledgeService struct {
|
||||
interfaces.KnowledgeService
|
||||
docs map[string]*types.Knowledge
|
||||
}
|
||||
|
||||
func (s *stubKnowledgeService) GetKnowledgeByIDOnly(_ context.Context, id string) (*types.Knowledge, error) {
|
||||
k, ok := s.docs[id]
|
||||
if !ok {
|
||||
return nil, errors.New("not found")
|
||||
}
|
||||
return k, nil
|
||||
}
|
||||
|
||||
func TestScopedKBContextEnablesWritesOnlyForAuthorizedKnowledgeBases(t *testing.T) {
|
||||
own := &types.KnowledgeBase{ID: "kb-own", TenantID: 1}
|
||||
foreign := &types.KnowledgeBase{ID: "kb-foreign", TenantID: 2}
|
||||
srv := newScopeTestServer(own, foreign)
|
||||
ep := &types.MCPEndpoint{ID: "ep", TenantID: 1, Tools: types.StringArray{types.MCPEndpointToolAddDocument}}
|
||||
ctx := mcpCallContext(1, ep)
|
||||
|
||||
if err := access.RequireKBWrite(ctx, own); err == nil {
|
||||
t.Fatal("no grant must exist before scopedKBContext runs")
|
||||
}
|
||||
scoped, err := srv.scopedKBContext(ctx, own, types.OrgRoleEditor)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := access.RequireKBWrite(scoped, own); err != nil {
|
||||
t.Fatalf("owned knowledge base must be writable after grant: %v", err)
|
||||
}
|
||||
if got := types.MustTenantIDFromContext(scoped); got != 1 {
|
||||
t.Fatalf("execution tenant = %d, want owner 1", got)
|
||||
}
|
||||
if _, err := srv.scopedKBContext(ctx, foreign, types.OrgRoleEditor); err == nil {
|
||||
t.Fatal("foreign knowledge base must not receive a write grant")
|
||||
}
|
||||
|
||||
readOnly := &types.MCPEndpoint{
|
||||
ID: "ep2", TenantID: 1, Tools: types.StringArray{types.MCPEndpointToolSearchKnowledge},
|
||||
}
|
||||
roScoped, err := srv.scopedKBContext(mcpCallContext(1, readOnly), own, types.OrgRoleEditor)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := access.RequireKBWrite(roScoped, own); err == nil {
|
||||
t.Fatal("an endpoint without ingest tools must lack the ingest capability and be refused")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSharedKnowledgeBaseRunsUnderOwnerTenant(t *testing.T) {
|
||||
shared := &types.KnowledgeBase{ID: "kb-shared", TenantID: 2, Name: "Shared"}
|
||||
srv := newScopeTestServer(shared)
|
||||
srv.kbShareService = &stubKBShareService{shared: map[string]types.OrgMemberRole{"kb-shared": types.OrgRoleEditor}}
|
||||
srv.tenantService = &stubTenantService{tenants: map[uint64]*types.Tenant{2: {ID: 2, Name: "Owner"}}}
|
||||
srv.knowledgeService = &stubKnowledgeService{docs: map[string]*types.Knowledge{
|
||||
"doc-shared": {ID: "doc-shared", TenantID: 2, KnowledgeBaseID: "kb-shared"},
|
||||
"doc-spoof": {ID: "doc-spoof", TenantID: 1, KnowledgeBaseID: "kb-shared"},
|
||||
}}
|
||||
ep := &types.MCPEndpoint{
|
||||
ID: "ep", TenantID: 1, KnowledgeBaseIDs: types.StringArray{"kb-shared"},
|
||||
Tools: types.StringArray{types.MCPEndpointToolUpdateDocument},
|
||||
}
|
||||
ctx := context.WithValue(mcpCallContext(1, ep), types.TenantInfoContextKey, &types.Tenant{ID: 1, Name: "Caller"})
|
||||
|
||||
// The shared knowledge base is visible through the organization share.
|
||||
kbs, err := srv.allowedKnowledgeBases(ctx, ep)
|
||||
if err != nil || len(kbs) != 1 {
|
||||
t.Fatalf("shared knowledge base must be in scope: %v %v", knowledgeBaseIDs(kbs), err)
|
||||
}
|
||||
|
||||
// Its document resolves even though it lives under tenant 2 ...
|
||||
k, kb, err := srv.knowledgeInScope(ctx, ep, "doc-shared")
|
||||
if err != nil || k.ID != "doc-shared" || kb.ID != "kb-shared" {
|
||||
t.Fatalf("shared document must be in scope: %v %v %v", k, kb, err)
|
||||
}
|
||||
// ... but a document whose tenant does not match its knowledge base is not.
|
||||
if _, _, err := srv.knowledgeInScope(ctx, ep, "doc-spoof"); err == nil {
|
||||
t.Fatal("document with mismatched tenant must be rejected")
|
||||
}
|
||||
|
||||
// Writes run under the owner tenant with an editor grant and owner TenantInfo.
|
||||
scoped, err := srv.scopedKBContext(ctx, kb, types.OrgRoleEditor)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := types.MustTenantIDFromContext(scoped); got != 2 {
|
||||
t.Fatalf("execution tenant = %d, want owner 2", got)
|
||||
}
|
||||
if info, ok := types.TenantInfoFromContext(scoped); !ok || info.ID != 2 {
|
||||
t.Fatalf("tenant info must be swapped to the owner, got %+v", info)
|
||||
}
|
||||
if err := access.RequireKBWrite(scoped, kb); err != nil {
|
||||
t.Fatalf("editor share must allow writes: %v", err)
|
||||
}
|
||||
if caller := types.CallerFromContext(scoped); caller.TenantID != 1 {
|
||||
t.Fatalf("caller must stay the endpoint tenant, got %+v", caller)
|
||||
}
|
||||
|
||||
// A viewer share must not mint a write grant.
|
||||
srv.kbShareService = &stubKBShareService{shared: map[string]types.OrgMemberRole{"kb-shared": types.OrgRoleViewer}}
|
||||
if _, err := srv.scopedKBContext(ctx, kb, types.OrgRoleEditor); err == nil {
|
||||
t.Fatal("viewer share must not allow writes")
|
||||
}
|
||||
if _, err := srv.scopedKBContext(ctx, kb, types.OrgRoleViewer); err != nil {
|
||||
t.Fatalf("viewer share must allow reads: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveAskAgentUsesEndpointAgentOnly(t *testing.T) {
|
||||
agents := &stubAgentService{agents: map[string]*types.CustomAgent{
|
||||
types.BuiltinQuickAnswerID: {ID: types.BuiltinQuickAnswerID, TenantID: 1, IsBuiltin: true},
|
||||
types.BuiltinWikiFixerID: {ID: types.BuiltinWikiFixerID, TenantID: 1, IsBuiltin: true},
|
||||
"agent-own": {ID: "agent-own", TenantID: 1},
|
||||
"agent-foreign": {ID: "agent-foreign", TenantID: 2},
|
||||
}}
|
||||
srv := &Server{agentService: agents}
|
||||
|
||||
got, err := srv.resolveAskAgent(context.Background(), &types.MCPEndpoint{ID: "ep", TenantID: 1})
|
||||
if err != nil || got.ID != types.BuiltinQuickAnswerID {
|
||||
t.Fatalf("empty default must fall back to quick answer: %v %v", got, err)
|
||||
}
|
||||
got, err = srv.resolveAskAgent(context.Background(),
|
||||
&types.MCPEndpoint{ID: "ep", TenantID: 1, DefaultAgentID: "agent-own"})
|
||||
if err != nil || got.ID != "agent-own" {
|
||||
t.Fatalf("configured tenant agent must be used: %v %v", got, err)
|
||||
}
|
||||
for _, bad := range []string{types.BuiltinWikiFixerID, "agent-foreign", "agent-missing"} {
|
||||
_, err := srv.resolveAskAgent(context.Background(),
|
||||
&types.MCPEndpoint{ID: "ep", TenantID: 1, DefaultAgentID: bad})
|
||||
if err == nil {
|
||||
t.Fatalf("agent %q must be refused", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAskToolHasNoAgentParameter(t *testing.T) {
|
||||
tool := askTool()
|
||||
if _, ok := tool.InputSchema.Properties["agent_id"]; ok {
|
||||
t.Fatal("ask must not let clients pick an agent")
|
||||
}
|
||||
if tool.Annotations.ReadOnlyHint != nil && *tool.Annotations.ReadOnlyHint {
|
||||
t.Fatal("ask must not advertise itself as read-only")
|
||||
}
|
||||
add := addDocumentTool()
|
||||
if add.Annotations.DestructiveHint == nil || !*add.Annotations.DestructiveHint {
|
||||
t.Fatal("add_document must advertise a mutation")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
// Package mcpserver hosts Academy's own MCP server surface: the Streamable
|
||||
// HTTP endpoint that external MCP clients (Claude Desktop, Cursor, VS Code
|
||||
// Copilot, ...) connect to. Every request is authenticated by
|
||||
// middleware.MCPEndpointAuth against a workspace MCPEndpoint row, and the
|
||||
// endpoint's tool allowlist and knowledge-base scope decide what the client
|
||||
// can see and call.
|
||||
//
|
||||
// A single mcp-go server instance is registered with the full tool catalog;
|
||||
// per-endpoint visibility is applied through a tool filter (tools/list) and a
|
||||
// handler middleware (tools/call), both keyed off the endpoint on the request
|
||||
// context. The transport runs stateless so any replica can answer any call.
|
||||
package mcpserver
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"academy/internal/config"
|
||||
"academy/internal/logger"
|
||||
"academy/internal/ratelimit"
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
"github.com/mark3labs/mcp-go/mcp"
|
||||
"github.com/mark3labs/mcp-go/server"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const (
|
||||
serverName = "academy"
|
||||
serverVersion = "1.0.0"
|
||||
|
||||
rateLimitKeyPrefix = "mcp:endpoint:ratelimit:"
|
||||
lastUsedTouchEvery = time.Minute
|
||||
)
|
||||
|
||||
var errNoEndpoint = errors.New("mcp endpoint missing from request context")
|
||||
|
||||
// Server wires the tool catalog onto an mcp-go server and exposes it as an
|
||||
// http.Handler.
|
||||
type Server struct {
|
||||
kbService interfaces.KnowledgeBaseService
|
||||
knowledgeService interfaces.KnowledgeService
|
||||
chunkService interfaces.ChunkService
|
||||
wikiService interfaces.WikiPageService
|
||||
sessionService interfaces.SessionService
|
||||
messageService interfaces.MessageService
|
||||
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
|
||||
|
||||
limiter *ratelimit.Limiter
|
||||
lastTouch sync.Map // endpoint id -> time.Time of the last last_used_at write
|
||||
|
||||
mcp *server.MCPServer
|
||||
handler http.Handler
|
||||
}
|
||||
|
||||
// NewServer builds the MCP server and its Streamable HTTP transport.
|
||||
func NewServer(
|
||||
kbService interfaces.KnowledgeBaseService,
|
||||
knowledgeService interfaces.KnowledgeService,
|
||||
chunkService interfaces.ChunkService,
|
||||
wikiService interfaces.WikiPageService,
|
||||
sessionService interfaces.SessionService,
|
||||
messageService interfaces.MessageService,
|
||||
agentService interfaces.CustomAgentService,
|
||||
kbShareService interfaces.KBShareService,
|
||||
tenantService interfaces.TenantService,
|
||||
endpointRepo interfaces.MCPEndpointRepository,
|
||||
db *gorm.DB,
|
||||
cfg *config.Config,
|
||||
redisClient *redis.Client,
|
||||
resourceCatalog interfaces.ResourceCatalog,
|
||||
fileService interfaces.FileService,
|
||||
storageResolver interfaces.StorageBackendResolver,
|
||||
) *Server {
|
||||
s := &Server{
|
||||
kbService: kbService,
|
||||
knowledgeService: knowledgeService,
|
||||
chunkService: chunkService,
|
||||
wikiService: wikiService,
|
||||
sessionService: sessionService,
|
||||
messageService: messageService,
|
||||
agentService: agentService,
|
||||
kbShareService: kbShareService,
|
||||
tenantService: tenantService,
|
||||
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
|
||||
// lives for the whole process so the cleanup goroutine never stops.
|
||||
go s.limiter.StartCleanup(make(chan struct{}))
|
||||
s.mcp = server.NewMCPServer(
|
||||
serverName,
|
||||
serverVersion,
|
||||
server.WithToolCapabilities(false),
|
||||
server.WithRecovery(),
|
||||
server.WithToolFilter(s.filterTools),
|
||||
server.WithToolHandlerMiddleware(s.guardTool),
|
||||
server.WithInstructions(serverInstructions),
|
||||
)
|
||||
s.mcp.AddTools(s.toolCatalog()...)
|
||||
s.handler = server.NewStreamableHTTPServer(
|
||||
s.mcp,
|
||||
server.WithStateLess(true),
|
||||
)
|
||||
return s
|
||||
}
|
||||
|
||||
// Handler returns the http.Handler to mount under /mcp/:endpoint_id. The
|
||||
// caller must run MCPEndpointAuth first; the handler trusts the context.
|
||||
func (s *Server) Handler() http.Handler {
|
||||
return s.handler
|
||||
}
|
||||
|
||||
const serverInstructions = "Academy knowledge workspace. Start with list_knowledge_bases to see what is in scope, " +
|
||||
"then use search_knowledge for semantic questions, grep_chunks for exact keywords, read_document to read " +
|
||||
"a whole document, and ask to get a synthesized answer with citations. Wiki tools browse the generated " +
|
||||
"wiki when a knowledge base has one. Write tools (add/update/delete_document) exist only on endpoints " +
|
||||
"that enabled them."
|
||||
|
||||
// endpointFromContext returns the endpoint authenticated for this call.
|
||||
func endpointFromContext(ctx context.Context) (*types.MCPEndpoint, error) {
|
||||
ep, ok := ctx.Value(types.MCPEndpointContextKey).(*types.MCPEndpoint)
|
||||
if !ok || ep == nil {
|
||||
return nil, errNoEndpoint
|
||||
}
|
||||
return ep, nil
|
||||
}
|
||||
|
||||
// filterTools hides catalog entries the endpoint did not enable.
|
||||
func (s *Server) filterTools(ctx context.Context, all []mcp.Tool) []mcp.Tool {
|
||||
ep, err := endpointFromContext(ctx)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
out := make([]mcp.Tool, 0, len(all))
|
||||
for _, t := range all {
|
||||
if ep.HasTool(t.Name) {
|
||||
out = append(out, t)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// guardTool enforces the allowlist and rate limit on every tools/call, so a
|
||||
// client cannot invoke a hidden tool by name.
|
||||
func (s *Server) guardTool(next server.ToolHandlerFunc) server.ToolHandlerFunc {
|
||||
return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
ep, err := endpointFromContext(ctx)
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("unauthorized"), nil
|
||||
}
|
||||
if !ep.HasTool(req.Params.Name) {
|
||||
return mcp.NewToolResultErrorf("tool %q is not enabled on this endpoint", req.Params.Name), nil
|
||||
}
|
||||
if !s.limiter.Allow(ctx, ep.ID, ep.RateLimitPerMinute) {
|
||||
return mcp.NewToolResultError("rate limit exceeded for this endpoint, retry shortly"), nil
|
||||
}
|
||||
s.touchLastUsed(ctx, ep.ID)
|
||||
result, err := next(ctx, req)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
return s.rewriteResourceURLs(ctx, ep, result), nil
|
||||
}
|
||||
}
|
||||
|
||||
// touchLastUsed records activity at most once a minute per endpoint.
|
||||
func (s *Server) touchLastUsed(ctx context.Context, endpointID string) {
|
||||
if s.endpointRepo == nil {
|
||||
return
|
||||
}
|
||||
now := time.Now()
|
||||
if prev, ok := s.lastTouch.Load(endpointID); ok {
|
||||
if last, ok := prev.(time.Time); ok && now.Sub(last) < lastUsedTouchEvery {
|
||||
return
|
||||
}
|
||||
}
|
||||
s.lastTouch.Store(endpointID, now)
|
||||
go func() {
|
||||
bg, cancel := context.WithTimeout(logger.CloneContext(ctx), 5*time.Second)
|
||||
defer cancel()
|
||||
if err := s.endpointRepo.TouchLastUsed(bg, endpointID); err != nil {
|
||||
logger.Warnf(bg, "[mcpserver] touch last_used failed for %s: %v", endpointID, err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// toolCatalog lists every tool with its handler. Order matches the settings
|
||||
// catalog so tools/list is stable.
|
||||
func (s *Server) toolCatalog() []server.ServerTool {
|
||||
return []server.ServerTool{
|
||||
{Tool: listKnowledgeBasesTool(), Handler: s.handleListKnowledgeBases},
|
||||
{Tool: searchKnowledgeTool(), Handler: s.handleSearchKnowledge},
|
||||
{Tool: grepChunksTool(), Handler: s.handleGrepChunks},
|
||||
{Tool: listDocumentsTool(), Handler: s.handleListDocuments},
|
||||
{Tool: readDocumentTool(), Handler: s.handleReadDocument},
|
||||
{Tool: askTool(), Handler: s.handleAsk},
|
||||
{Tool: wikiSearchTool(), Handler: s.handleWikiSearch},
|
||||
{Tool: wikiReadPageTool(), Handler: s.handleWikiReadPage},
|
||||
{Tool: wikiIndexTool(), Handler: s.handleWikiIndex},
|
||||
{Tool: addDocumentTool(), Handler: s.handleAddDocument},
|
||||
{Tool: updateDocumentTool(), Handler: s.handleUpdateDocument},
|
||||
{Tool: deleteDocumentTool(), Handler: s.handleDeleteDocument},
|
||||
}
|
||||
}
|
||||
|
||||
// toolResultFromAgentTool converts an agent tool result into an MCP result.
|
||||
// Agent tools already format their Output for a model reader, so the text
|
||||
// is passed through; Data is attached as structured content when present.
|
||||
func toolResultFromAgentTool(res *types.ToolResult, err error) *mcp.CallToolResult {
|
||||
if err != nil && (res == nil || res.Error == "") {
|
||||
return mcp.NewToolResultError(err.Error())
|
||||
}
|
||||
if res == nil {
|
||||
return mcp.NewToolResultError("tool returned no result")
|
||||
}
|
||||
if !res.Success {
|
||||
msg := res.Error
|
||||
if msg == "" {
|
||||
msg = res.Output
|
||||
}
|
||||
if msg == "" {
|
||||
msg = "tool failed"
|
||||
}
|
||||
return mcp.NewToolResultError(msg)
|
||||
}
|
||||
if len(res.Data) > 0 {
|
||||
return mcp.NewToolResultStructured(res.Data, res.Output)
|
||||
}
|
||||
return mcp.NewToolResultText(res.Output)
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
package mcpserver
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// recordingEndpointRepo captures last_used touches so the guard's background
|
||||
// write can be asserted (and never dereferences a nil repository).
|
||||
type recordingEndpointRepo struct {
|
||||
interfaces.MCPEndpointRepository
|
||||
touched chan string
|
||||
}
|
||||
|
||||
func (r *recordingEndpointRepo) TouchLastUsed(_ context.Context, id string) error {
|
||||
select {
|
||||
case r.touched <- id:
|
||||
default:
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// newTestEngine mounts the MCP server behind a middleware that injects the
|
||||
// given endpoint straight onto the request context, standing in for
|
||||
// middleware.MCPEndpointAuth so the transport, tool filter and call guard
|
||||
// can be exercised without a database.
|
||||
func newTestEngine(t *testing.T, ep *types.MCPEndpoint) *gin.Engine {
|
||||
engine, _ := newTestEngineWithRepo(t, ep)
|
||||
return engine
|
||||
}
|
||||
|
||||
func newTestEngineWithRepo(t *testing.T, ep *types.MCPEndpoint) (*gin.Engine, *recordingEndpointRepo) {
|
||||
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, nil, nil, nil)
|
||||
r := gin.New()
|
||||
inject := func(c *gin.Context) {
|
||||
if ep != nil {
|
||||
ctx := context.WithValue(c.Request.Context(), types.MCPEndpointContextKey, ep)
|
||||
ctx = context.WithValue(ctx, types.TenantIDContextKey, ep.TenantID)
|
||||
c.Request = c.Request.WithContext(ctx)
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
r.POST("/mcp/:endpoint_id", inject, gin.WrapH(srv.Handler()))
|
||||
return r, repo
|
||||
}
|
||||
|
||||
func rpc(t *testing.T, r *gin.Engine, method string, params any) map[string]any {
|
||||
t.Helper()
|
||||
body, _ := json.Marshal(map[string]any{
|
||||
"jsonrpc": "2.0",
|
||||
"id": 1,
|
||||
"method": method,
|
||||
"params": params,
|
||||
})
|
||||
req := httptest.NewRequest(http.MethodPost, "/mcp/ep-1", bytes.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Accept", "application/json, text/event-stream")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("%s: status %d body %s", method, w.Code, w.Body.String())
|
||||
}
|
||||
raw := w.Body.String()
|
||||
// Streamable HTTP may answer as SSE; unwrap the data line if so.
|
||||
if strings.HasPrefix(strings.TrimSpace(raw), "event:") || strings.HasPrefix(strings.TrimSpace(raw), "data:") {
|
||||
for _, line := range strings.Split(raw, "\n") {
|
||||
if strings.HasPrefix(line, "data:") {
|
||||
raw = strings.TrimSpace(strings.TrimPrefix(line, "data:"))
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
var out map[string]any
|
||||
if err := json.Unmarshal([]byte(raw), &out); err != nil {
|
||||
t.Fatalf("%s: bad json %q: %v", method, raw, err)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func toolNames(t *testing.T, resp map[string]any) []string {
|
||||
t.Helper()
|
||||
result, _ := resp["result"].(map[string]any)
|
||||
tools, _ := result["tools"].([]any)
|
||||
names := make([]string, 0, len(tools))
|
||||
for _, tl := range tools {
|
||||
m, _ := tl.(map[string]any)
|
||||
names = append(names, m["name"].(string))
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
func TestToolsListIsFilteredByEndpoint(t *testing.T) {
|
||||
ep := &types.MCPEndpoint{
|
||||
ID: "ep-1", TenantID: 1, Enabled: true, RateLimitPerMinute: 100,
|
||||
Tools: types.StringArray{types.MCPEndpointToolListKnowledgeBases, types.MCPEndpointToolAsk},
|
||||
}
|
||||
r := newTestEngine(t, ep)
|
||||
names := toolNames(t, rpc(t, r, "tools/list", map[string]any{}))
|
||||
sort.Strings(names)
|
||||
if len(names) != 2 || names[0] != types.MCPEndpointToolAsk || names[1] != types.MCPEndpointToolListKnowledgeBases {
|
||||
t.Fatalf("filtered tools = %v", names)
|
||||
}
|
||||
}
|
||||
|
||||
func TestToolsListEmptyWithoutEndpoint(t *testing.T) {
|
||||
r := newTestEngine(t, nil)
|
||||
if names := toolNames(t, rpc(t, r, "tools/list", map[string]any{})); len(names) != 0 {
|
||||
t.Fatalf("expected no tools without an endpoint, got %v", names)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCatalogMatchesSettingsCatalog(t *testing.T) {
|
||||
all := types.StringArray{}
|
||||
for _, def := range types.MCPEndpointToolCatalog() {
|
||||
all = append(all, def.Name)
|
||||
}
|
||||
ep := &types.MCPEndpoint{ID: "ep-1", TenantID: 1, Enabled: true, Tools: all}
|
||||
r := newTestEngine(t, ep)
|
||||
names := toolNames(t, rpc(t, r, "tools/list", map[string]any{}))
|
||||
if len(names) != len(all) {
|
||||
t.Fatalf("server exposes %d tools, catalog has %d: %v", len(names), len(all), names)
|
||||
}
|
||||
// tools/list is sorted by name; compare as sets.
|
||||
want := append([]string(nil), all...)
|
||||
sort.Strings(want)
|
||||
sort.Strings(names)
|
||||
for i := range want {
|
||||
if names[i] != want[i] {
|
||||
t.Fatalf("tool mismatch at %d: %q vs %q", i, names[i], want[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCallHiddenToolIsRefused(t *testing.T) {
|
||||
ep := &types.MCPEndpoint{
|
||||
ID: "ep-1", TenantID: 1, Enabled: true, RateLimitPerMinute: 100,
|
||||
Tools: types.StringArray{types.MCPEndpointToolListKnowledgeBases},
|
||||
}
|
||||
r := newTestEngine(t, ep)
|
||||
resp := rpc(t, r, "tools/call", map[string]any{
|
||||
"name": types.MCPEndpointToolDeleteDocument,
|
||||
"arguments": map[string]any{"knowledge_id": "k-1"},
|
||||
})
|
||||
// Filtered tools are unavailable at SDK dispatch, before a handler runs.
|
||||
err, _ := resp["error"].(map[string]any)
|
||||
if err["code"] != float64(-32602) || resp["result"] != nil {
|
||||
t.Fatalf("expected invalid-params protocol error, got %v", resp)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRateLimitPerEndpoint(t *testing.T) {
|
||||
ep := &types.MCPEndpoint{
|
||||
ID: "ep-1", TenantID: 1, Enabled: true, RateLimitPerMinute: 1,
|
||||
Tools: types.StringArray{types.MCPEndpointToolReadDocument},
|
||||
}
|
||||
r, repo := newTestEngineWithRepo(t, ep)
|
||||
call := func() string {
|
||||
resp := rpc(t, r, "tools/call", map[string]any{
|
||||
"name": types.MCPEndpointToolReadDocument,
|
||||
"arguments": map[string]any{},
|
||||
})
|
||||
result, _ := resp["result"].(map[string]any)
|
||||
content, _ := result["content"].([]any)
|
||||
first, _ := content[0].(map[string]any)
|
||||
return first["text"].(string)
|
||||
}
|
||||
// First call passes the guard and fails inside the handler on validation.
|
||||
if text := call(); !strings.Contains(text, "knowledge_id is required") {
|
||||
t.Fatalf("first call: %q", text)
|
||||
}
|
||||
if text := call(); !strings.Contains(text, "rate limit") {
|
||||
t.Fatalf("second call should be rate limited: %q", text)
|
||||
}
|
||||
select {
|
||||
case id := <-repo.touched:
|
||||
if id != "ep-1" {
|
||||
t.Fatalf("touched endpoint = %q", id)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("expected last_used_at to be touched after a guarded call")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTouchLastUsedToleratesMissingRepository(_ *testing.T) {
|
||||
srv := &Server{}
|
||||
srv.touchLastUsed(context.Background(), "ep-1") // must not panic
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package mcpserver
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/mark3labs/mcp-go/mcp"
|
||||
)
|
||||
|
||||
func TestReadOnlyEndpointToolsAreNotDestructive(t *testing.T) {
|
||||
for _, tool := range []mcp.Tool{
|
||||
listKnowledgeBasesTool(),
|
||||
searchKnowledgeTool(),
|
||||
grepChunksTool(),
|
||||
listDocumentsTool(),
|
||||
readDocumentTool(),
|
||||
wikiSearchTool(),
|
||||
wikiReadPageTool(),
|
||||
wikiIndexTool(),
|
||||
} {
|
||||
ann := tool.Annotations
|
||||
if ann.ReadOnlyHint == nil || !*ann.ReadOnlyHint {
|
||||
t.Fatalf("%s must be read-only", tool.Name)
|
||||
}
|
||||
if ann.DestructiveHint == nil || *ann.DestructiveHint {
|
||||
t.Fatalf("%s must not be destructive", tool.Name)
|
||||
}
|
||||
if ann.IdempotentHint == nil || !*ann.IdempotentHint {
|
||||
t.Fatalf("%s must be idempotent", tool.Name)
|
||||
}
|
||||
if ann.OpenWorldHint == nil || *ann.OpenWorldHint {
|
||||
t.Fatalf("%s must not be open-world", tool.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMutatingEndpointToolsStayDestructive(t *testing.T) {
|
||||
ask := askTool()
|
||||
if ask.Annotations.ReadOnlyHint == nil || *ask.Annotations.ReadOnlyHint {
|
||||
t.Fatal("ask must not be read-only")
|
||||
}
|
||||
if ask.Annotations.DestructiveHint == nil || !*ask.Annotations.DestructiveHint {
|
||||
t.Fatal("ask keeps the default destructive hint")
|
||||
}
|
||||
for _, tool := range []mcp.Tool{
|
||||
addDocumentTool(),
|
||||
updateDocumentTool(),
|
||||
deleteDocumentTool(),
|
||||
} {
|
||||
if tool.Annotations.DestructiveHint == nil || !*tool.Annotations.DestructiveHint {
|
||||
t.Fatalf("%s must stay destructive", tool.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,494 @@
|
||||
package mcpserver
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"academy/internal/event"
|
||||
"academy/internal/logger"
|
||||
"academy/internal/types"
|
||||
"github.com/google/uuid"
|
||||
"github.com/mark3labs/mcp-go/mcp"
|
||||
)
|
||||
|
||||
const (
|
||||
askTimeout = 4 * time.Minute
|
||||
askCompleteWaitTimeout = 15 * time.Second
|
||||
askSessionTitleMaxLen = 60
|
||||
askChannel = "mcp"
|
||||
)
|
||||
|
||||
func askTool() mcp.Tool {
|
||||
return mcp.NewTool(types.MCPEndpointToolAsk,
|
||||
mcp.WithDescription("Ask the workspace a question and get a synthesized answer with citations. "+
|
||||
"Academy retrieves from the knowledge bases in scope and runs the agent configured on this "+
|
||||
"endpoint. Pass the returned session_id on follow-up questions to keep the conversation going. "+
|
||||
"This can take up to a few minutes for agentic runs; prefer search_knowledge when you only need "+
|
||||
"raw passages."),
|
||||
mcp.WithString("question", mcp.Required(), mcp.Description("The question to answer")),
|
||||
mcp.WithString("session_id",
|
||||
mcp.Description("Session id returned by a previous ask call, to continue that conversation")),
|
||||
mcp.WithArray("knowledge_base_ids", mcp.WithStringItems(),
|
||||
mcp.Description("Optional knowledge base ids or names to retrieve from; defaults to the "+
|
||||
"endpoint scope or the agent's own configuration")),
|
||||
// Not read-only: it creates a session and messages, and the configured
|
||||
// agent may run its own tools. Clients must not auto-approve it.
|
||||
mcp.WithReadOnlyHintAnnotation(false),
|
||||
)
|
||||
}
|
||||
|
||||
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"`
|
||||
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) {
|
||||
ep, err := endpointFromContext(ctx)
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("unauthorized"), nil
|
||||
}
|
||||
question, err := req.RequireString("question")
|
||||
if err != nil || strings.TrimSpace(question) == "" {
|
||||
return mcp.NewToolResultError("question is required"), nil
|
||||
}
|
||||
question = strings.TrimSpace(question)
|
||||
|
||||
agent, err := s.resolveAskAgent(ctx, ep)
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError(err.Error()), nil
|
||||
}
|
||||
kbIDs, err := s.resolveAskKnowledgeBases(ctx, ep, agent, req.GetStringSlice("knowledge_base_ids", nil))
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError(err.Error()), nil
|
||||
}
|
||||
session, err := s.resolveAskSession(ctx, ep, req.GetString("session_id", ""), question)
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError(err.Error()), nil
|
||||
}
|
||||
|
||||
answer, refs, err := s.runQA(ctx, session, agent, question, kbIDs)
|
||||
if err != nil {
|
||||
return mcp.NewToolResultErrorFromErr("failed to answer", err), nil
|
||||
}
|
||||
structured := map[string]any{
|
||||
"answer": answer,
|
||||
"session_id": session.ID,
|
||||
"agent_id": agent.ID,
|
||||
"references": refs,
|
||||
}
|
||||
var text string
|
||||
if len(refs) > 0 {
|
||||
var b strings.Builder
|
||||
b.WriteString(answer)
|
||||
b.WriteString("\n\nSources:\n")
|
||||
for i, r := range refs {
|
||||
title := r.KnowledgeTitle
|
||||
if title == "" {
|
||||
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()
|
||||
} else {
|
||||
text = fmt.Sprintf("%s\n\nsession_id: %s", answer, session.ID)
|
||||
}
|
||||
return mcp.NewToolResultStructured(structured, text), nil
|
||||
}
|
||||
|
||||
// resolveAskAgent picks the agent configured on the endpoint. Callers cannot
|
||||
// name an agent: letting a client choose any tenant agent (or an internal
|
||||
// builtin such as the wiki fixer or skill installer, which carry write and
|
||||
// shell tools) would bypass the endpoint's tool allowlist.
|
||||
func (s *Server) resolveAskAgent(ctx context.Context, ep *types.MCPEndpoint) (*types.CustomAgent, error) {
|
||||
agentID := strings.TrimSpace(ep.DefaultAgentID)
|
||||
if agentID == "" {
|
||||
agentID = types.BuiltinQuickAnswerID
|
||||
}
|
||||
agent, err := s.agentService.GetAgentByID(ctx, agentID)
|
||||
if err != nil || agent == nil {
|
||||
return nil, fmt.Errorf("the agent configured on this endpoint (%q) is not available", agentID)
|
||||
}
|
||||
if !types.MCPEndpointAgentAllowed(agent, ep.TenantID) {
|
||||
return nil, fmt.Errorf("the agent configured on this endpoint (%q) is not available", agentID)
|
||||
}
|
||||
return agent, nil
|
||||
}
|
||||
|
||||
// resolveAskKnowledgeBases picks the retrieval scope for one ask call:
|
||||
// explicit selectors win; otherwise a restricted endpoint pins its own list;
|
||||
// otherwise the agent's configuration decides, except that an agent with no
|
||||
// knowledge bases of its own falls back to everything the endpoint can see
|
||||
// so the call does not fail with "no search targets".
|
||||
func (s *Server) resolveAskKnowledgeBases(
|
||||
ctx context.Context, ep *types.MCPEndpoint, agent *types.CustomAgent, requested []string,
|
||||
) ([]string, error) {
|
||||
hasRequest := false
|
||||
for _, r := range requested {
|
||||
if strings.TrimSpace(r) != "" {
|
||||
hasRequest = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if hasRequest {
|
||||
kbs, err := s.selectKnowledgeBases(ctx, ep, requested)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return knowledgeBaseIDs(kbs), nil
|
||||
}
|
||||
if ep.RestrictsKnowledgeBases() {
|
||||
kbs, err := s.allowedKnowledgeBases(ctx, ep)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return knowledgeBaseIDs(kbs), nil
|
||||
}
|
||||
mode := strings.ToLower(strings.TrimSpace(agent.Config.KBSelectionMode))
|
||||
agentHasNoKBs := mode == "none" || ((mode == "selected" || mode == "") && len(agent.Config.KnowledgeBases) == 0)
|
||||
if agentHasNoKBs {
|
||||
kbs, err := s.allowedKnowledgeBases(ctx, ep)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return knowledgeBaseIDs(kbs), nil
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (s *Server) resolveAskSession(
|
||||
ctx context.Context, ep *types.MCPEndpoint, sessionID, question string,
|
||||
) (*types.Session, error) {
|
||||
ownerID := types.MCPEndpointPrincipal(ep.TenantID, ep.ID).StorageID()
|
||||
if sessionID = strings.TrimSpace(sessionID); sessionID != "" {
|
||||
session, err := s.sessionService.GetSessionByID(ctx, ep.TenantID, sessionID)
|
||||
if err != nil || session == nil || session.UserID != ownerID {
|
||||
return nil, fmt.Errorf("session %q was not found on this endpoint", sessionID)
|
||||
}
|
||||
return session, nil
|
||||
}
|
||||
title := question
|
||||
if runes := []rune(title); len(runes) > askSessionTitleMaxLen {
|
||||
title = string(runes[:askSessionTitleMaxLen])
|
||||
}
|
||||
created, err := s.sessionService.CreateSession(ctx, &types.Session{
|
||||
TenantID: ep.TenantID,
|
||||
Title: title,
|
||||
Description: "MCP endpoint " + ep.Name,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create session: %w", err)
|
||||
}
|
||||
if err := s.sessionService.SetSessionOwnerID(ctx, ep.TenantID, created.ID, ownerID); err != nil {
|
||||
return nil, fmt.Errorf("failed to bind session: %w", err)
|
||||
}
|
||||
created.UserID = ownerID
|
||||
created.OwnerAuthSource = types.AuthSourceForBoundOwnerID(ownerID)
|
||||
return created, nil
|
||||
}
|
||||
|
||||
// runQA executes one turn synchronously and returns the final answer and
|
||||
// the references it cited. It mirrors the IM channel's non-streaming path.
|
||||
func (s *Server) runQA(
|
||||
ctx context.Context, session *types.Session, agent *types.CustomAgent, question string, kbIDs []string,
|
||||
) (string, []askReference, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, askTimeout)
|
||||
defer cancel()
|
||||
|
||||
requestID := uuid.New().String()
|
||||
userMsg, err := s.messageService.CreateMessage(ctx, &types.Message{
|
||||
SessionID: session.ID,
|
||||
Role: "user",
|
||||
Content: question,
|
||||
RequestID: requestID,
|
||||
CreatedAt: time.Now(),
|
||||
IsCompleted: true,
|
||||
Channel: askChannel,
|
||||
})
|
||||
if err != nil {
|
||||
return "", nil, fmt.Errorf("failed to create user message: %w", err)
|
||||
}
|
||||
assistantMsg, err := s.messageService.CreateMessage(ctx, &types.Message{
|
||||
SessionID: session.ID,
|
||||
Role: "assistant",
|
||||
RequestID: requestID,
|
||||
CreatedAt: time.Now(),
|
||||
IsCompleted: false,
|
||||
Channel: askChannel,
|
||||
})
|
||||
if err != nil {
|
||||
return "", nil, fmt.Errorf("failed to create assistant message: %w", err)
|
||||
}
|
||||
|
||||
var (
|
||||
mu sync.Mutex
|
||||
answer strings.Builder
|
||||
final string
|
||||
refs []*types.SearchResult
|
||||
qaErr error
|
||||
done = make(chan struct{})
|
||||
complete = make(chan struct{})
|
||||
doneOnce sync.Once
|
||||
compOnce sync.Once
|
||||
)
|
||||
closeDone := func() { doneOnce.Do(func() { close(done) }) }
|
||||
closeComplete := func() { compOnce.Do(func() { close(complete) }) }
|
||||
|
||||
bus := event.NewEventBus()
|
||||
bus.On(event.EventAgentFinalAnswer, func(_ context.Context, evt event.Event) error {
|
||||
data, ok := evt.Data.(event.AgentFinalAnswerData)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
mu.Lock()
|
||||
answer.WriteString(data.Content)
|
||||
mu.Unlock()
|
||||
if data.Done {
|
||||
closeDone()
|
||||
}
|
||||
return nil
|
||||
})
|
||||
bus.On(event.EventAgentReferences, func(_ context.Context, evt event.Event) error {
|
||||
data, ok := evt.Data.(event.AgentReferencesData)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
mu.Lock()
|
||||
collectReferences(&refs, data.References)
|
||||
mu.Unlock()
|
||||
return nil
|
||||
})
|
||||
bus.On(event.EventAgentComplete, func(_ context.Context, evt event.Event) error {
|
||||
data, ok := evt.Data.(event.AgentCompleteData)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
mu.Lock()
|
||||
if data.FinalAnswer != "" {
|
||||
final = data.FinalAnswer
|
||||
}
|
||||
if len(data.KnowledgeRefs) > 0 {
|
||||
var completeRefs []*types.SearchResult
|
||||
collectReferences(&completeRefs, data.KnowledgeRefs)
|
||||
if len(completeRefs) > 0 {
|
||||
refs = completeRefs
|
||||
}
|
||||
}
|
||||
mu.Unlock()
|
||||
closeComplete()
|
||||
return nil
|
||||
})
|
||||
bus.On(event.EventError, func(_ context.Context, evt event.Event) error {
|
||||
data, ok := evt.Data.(event.ErrorData)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
mu.Lock()
|
||||
qaErr = fmt.Errorf("%s", data.Error)
|
||||
mu.Unlock()
|
||||
closeDone()
|
||||
closeComplete()
|
||||
return nil
|
||||
})
|
||||
|
||||
useAgent := agent.IsAgentMode()
|
||||
go func() {
|
||||
if useAgent {
|
||||
defer closeDone()
|
||||
defer closeComplete()
|
||||
}
|
||||
req := &types.QARequest{
|
||||
Session: session,
|
||||
Query: question,
|
||||
AssistantMessageID: assistantMsg.ID,
|
||||
UserMessageID: userMsg.ID,
|
||||
CustomAgent: agent,
|
||||
KnowledgeBaseIDs: kbIDs,
|
||||
// Web search is never enabled from the MCP surface: the builtin
|
||||
// quick-answer agent turns it on by default, which would make an
|
||||
// otherwise read-only endpoint reach the public internet.
|
||||
WebSearchEnabled: false,
|
||||
}
|
||||
var runErr error
|
||||
if useAgent {
|
||||
runErr = s.sessionService.AgentQA(ctx, req, bus)
|
||||
} else {
|
||||
runErr = s.sessionService.KnowledgeQA(ctx, req, bus)
|
||||
}
|
||||
if runErr != nil {
|
||||
mu.Lock()
|
||||
if qaErr == nil {
|
||||
qaErr = runErr
|
||||
}
|
||||
mu.Unlock()
|
||||
closeDone()
|
||||
closeComplete()
|
||||
}
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-done:
|
||||
if useAgent {
|
||||
timer := time.NewTimer(askCompleteWaitTimeout)
|
||||
select {
|
||||
case <-complete:
|
||||
case <-ctx.Done():
|
||||
case <-timer.C:
|
||||
logger.Warnf(ctx, "[mcpserver] ask timed out waiting for agent completion: session=%s", session.ID)
|
||||
}
|
||||
timer.Stop()
|
||||
}
|
||||
case <-ctx.Done():
|
||||
assistantMsg.Content = "The answer was interrupted before completion."
|
||||
assistantMsg.IsCompleted = true
|
||||
if updateErr := s.messageService.UpdateMessage(context.WithoutCancel(ctx), assistantMsg); updateErr != nil {
|
||||
logger.Warnf(ctx, "[mcpserver] failed to finalize interrupted message: %v", updateErr)
|
||||
}
|
||||
return "", nil, fmt.Errorf("answer timed out: %w", ctx.Err())
|
||||
}
|
||||
|
||||
mu.Lock()
|
||||
text := answer.String()
|
||||
if strings.TrimSpace(text) == "" && final != "" {
|
||||
text = final
|
||||
}
|
||||
collected := append([]*types.SearchResult(nil), refs...)
|
||||
runErr := qaErr
|
||||
mu.Unlock()
|
||||
|
||||
if strings.TrimSpace(text) == "" && runErr != nil {
|
||||
assistantMsg.Content = "The answer failed: " + runErr.Error()
|
||||
assistantMsg.IsCompleted = true
|
||||
if updateErr := s.messageService.UpdateMessage(context.WithoutCancel(ctx), assistantMsg); updateErr != nil {
|
||||
logger.Warnf(ctx, "[mcpserver] failed to finalize failed message: %v", updateErr)
|
||||
}
|
||||
return "", nil, runErr
|
||||
}
|
||||
if strings.TrimSpace(text) == "" {
|
||||
text = "No answer could be produced for this question."
|
||||
}
|
||||
assistantMsg.Content = text
|
||||
assistantMsg.IsCompleted = true
|
||||
if len(collected) > 0 {
|
||||
assistantMsg.KnowledgeReferences = types.References(collected)
|
||||
}
|
||||
if err := s.messageService.UpdateMessage(context.WithoutCancel(ctx), assistantMsg); err != nil {
|
||||
logger.Warnf(ctx, "[mcpserver] failed to persist assistant message: %v", err)
|
||||
}
|
||||
return text, summarizeReferences(collected), nil
|
||||
}
|
||||
|
||||
func collectReferences(dst *[]*types.SearchResult, raw interface{}) {
|
||||
switch v := raw.(type) {
|
||||
case []*types.SearchResult:
|
||||
*dst = append(*dst, v...)
|
||||
case []interface{}:
|
||||
for _, item := range v {
|
||||
if sr, ok := item.(*types.SearchResult); ok {
|
||||
*dst = append(*dst, sr)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const askExcerptMaxRunes = 300
|
||||
|
||||
func summarizeReferences(refs []*types.SearchResult) []askReference {
|
||||
out := make([]askReference, 0, len(refs))
|
||||
seen := map[string]int{}
|
||||
for _, r := range refs {
|
||||
if r == nil {
|
||||
continue
|
||||
}
|
||||
key := r.ID
|
||||
if key == "" {
|
||||
key = r.KnowledgeID + ":" + fmt.Sprint(r.ChunkIndex)
|
||||
}
|
||||
if index, dup := seen[key]; dup {
|
||||
out[index].Images = summarizeReferenceImages(r.ImageInfo, out[index].Images)
|
||||
continue
|
||||
}
|
||||
seen[key] = len(out)
|
||||
out = append(out, askReference{
|
||||
KnowledgeID: r.KnowledgeID,
|
||||
KnowledgeTitle: r.KnowledgeTitle,
|
||||
ChunkID: r.ID,
|
||||
Score: r.Score,
|
||||
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"
|
||||
|
||||
"academy/internal/event"
|
||||
"academy/internal/types"
|
||||
"academy/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://academy.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://")
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
package mcpserver
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"academy/internal/application/access"
|
||||
"academy/internal/types"
|
||||
"github.com/mark3labs/mcp-go/mcp"
|
||||
)
|
||||
|
||||
func addDocumentTool() mcp.Tool {
|
||||
return mcp.NewTool(types.MCPEndpointToolAddDocument,
|
||||
mcp.WithDescription("Add a document to a knowledge base from Markdown text or from a URL. Text documents "+
|
||||
"are stored as editable Markdown pages; URLs are fetched and parsed asynchronously. Returns the new "+
|
||||
"document id."),
|
||||
mcp.WithString("knowledge_base_id", mcp.Required(), mcp.Description("Knowledge base id or exact name")),
|
||||
mcp.WithString("title", mcp.Required(), mcp.Description("Document title")),
|
||||
mcp.WithString("content", mcp.Description("Markdown content; required unless url is given")),
|
||||
mcp.WithString("url", mcp.Description("Web page or file URL to import instead of content")),
|
||||
mcp.WithBoolean("publish", mcp.Description("For text documents: publish immediately (default true) or keep "+
|
||||
"as draft")),
|
||||
mcp.WithReadOnlyHintAnnotation(false),
|
||||
mcp.WithDestructiveHintAnnotation(true),
|
||||
)
|
||||
}
|
||||
|
||||
func updateDocumentTool() mcp.Tool {
|
||||
return mcp.NewTool(types.MCPEndpointToolUpdateDocument,
|
||||
mcp.WithDescription("Replace the content (and optionally the title) of a Markdown document created from "+
|
||||
"text. The document is re-indexed asynchronously."),
|
||||
mcp.WithString("knowledge_id", mcp.Required(), mcp.Description("Document id")),
|
||||
mcp.WithString("content", mcp.Required(), mcp.Description("New Markdown content")),
|
||||
mcp.WithString("title", mcp.Description("New title; keeps the current title when omitted")),
|
||||
mcp.WithBoolean("publish", mcp.Description("Publish (default true) or keep as draft")),
|
||||
mcp.WithDestructiveHintAnnotation(true),
|
||||
)
|
||||
}
|
||||
|
||||
func deleteDocumentTool() mcp.Tool {
|
||||
return mcp.NewTool(types.MCPEndpointToolDeleteDocument,
|
||||
mcp.WithDescription("Permanently delete a document and its index data from its knowledge base."),
|
||||
mcp.WithString("knowledge_id", mcp.Required(), mcp.Description("Document id")),
|
||||
mcp.WithDestructiveHintAnnotation(true),
|
||||
)
|
||||
}
|
||||
|
||||
func manualStatus(publish bool) string {
|
||||
if publish {
|
||||
return types.ManualKnowledgeStatusPublish
|
||||
}
|
||||
return types.ManualKnowledgeStatusDraft
|
||||
}
|
||||
|
||||
func (s *Server) handleAddDocument(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
ep, err := endpointFromContext(ctx)
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("unauthorized"), nil
|
||||
}
|
||||
selector, err := req.RequireString("knowledge_base_id")
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("knowledge_base_id is required"), nil
|
||||
}
|
||||
title := strings.TrimSpace(req.GetString("title", ""))
|
||||
if title == "" {
|
||||
return mcp.NewToolResultError("title is required"), nil
|
||||
}
|
||||
content := req.GetString("content", "")
|
||||
url := strings.TrimSpace(req.GetString("url", ""))
|
||||
if strings.TrimSpace(content) == "" && url == "" {
|
||||
return mcp.NewToolResultError("either content or url is required"), nil
|
||||
}
|
||||
kbs, err := s.selectKnowledgeBases(ctx, ep, []string{selector})
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError(err.Error()), nil
|
||||
}
|
||||
kb := kbs[0]
|
||||
ctx, err = s.scopedKBContext(ctx, kb, types.OrgRoleEditor)
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError(err.Error()), nil
|
||||
}
|
||||
if err := access.RequireKBWrite(ctx, kb); err != nil {
|
||||
return mcp.NewToolResultError("this endpoint is not allowed to write to knowledge base " + kb.ID), nil
|
||||
}
|
||||
|
||||
var created *types.Knowledge
|
||||
if url != "" {
|
||||
created, err = s.knowledgeService.CreateKnowledgeFromURL(
|
||||
ctx, kb.ID, url, "", "", nil, title, nil, askChannel, nil,
|
||||
)
|
||||
} else {
|
||||
created, err = s.knowledgeService.CreateKnowledgeFromManual(ctx, kb.ID, &types.ManualKnowledgePayload{
|
||||
Title: title,
|
||||
Content: content,
|
||||
Status: manualStatus(req.GetBool("publish", true)),
|
||||
Channel: askChannel,
|
||||
}, askChannel)
|
||||
}
|
||||
if err != nil {
|
||||
return mcp.NewToolResultErrorFromErr("failed to add document", err), nil
|
||||
}
|
||||
return jsonResult(map[string]any{
|
||||
"knowledge_base_id": kb.ID,
|
||||
"document": summarizeKnowledge(created),
|
||||
"note": "Indexing runs asynchronously; the document becomes searchable once parse_status is " +
|
||||
"completed.",
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleUpdateDocument(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
ep, err := endpointFromContext(ctx)
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("unauthorized"), nil
|
||||
}
|
||||
knowledgeID, err := req.RequireString("knowledge_id")
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("knowledge_id is required"), nil
|
||||
}
|
||||
content := req.GetString("content", "")
|
||||
if strings.TrimSpace(content) == "" {
|
||||
return mcp.NewToolResultError("content is required"), nil
|
||||
}
|
||||
existing, kb, err := s.knowledgeInScope(ctx, ep, knowledgeID)
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError(err.Error()), nil
|
||||
}
|
||||
ctx, err = s.scopedKBContext(ctx, kb, types.OrgRoleEditor)
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError(err.Error()), nil
|
||||
}
|
||||
title := strings.TrimSpace(req.GetString("title", ""))
|
||||
if title == "" {
|
||||
title = existing.Title
|
||||
}
|
||||
updated, err := s.knowledgeService.UpdateManualKnowledge(ctx, existing.ID, &types.ManualKnowledgePayload{
|
||||
Title: title,
|
||||
Content: content,
|
||||
Status: manualStatus(req.GetBool("publish", true)),
|
||||
Channel: askChannel,
|
||||
})
|
||||
if err != nil {
|
||||
return mcp.NewToolResultErrorFromErr("failed to update document", err), nil
|
||||
}
|
||||
return jsonResult(map[string]any{
|
||||
"document": summarizeKnowledge(updated),
|
||||
"note": "Re-indexing runs asynchronously.",
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleDeleteDocument(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
ep, err := endpointFromContext(ctx)
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("unauthorized"), nil
|
||||
}
|
||||
knowledgeID, err := req.RequireString("knowledge_id")
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("knowledge_id is required"), nil
|
||||
}
|
||||
existing, kb, err := s.knowledgeInScope(ctx, ep, knowledgeID)
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError(err.Error()), nil
|
||||
}
|
||||
ctx, err = s.scopedKBContext(ctx, kb, types.OrgRoleEditor)
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError(err.Error()), nil
|
||||
}
|
||||
if err := s.knowledgeService.DeleteKnowledge(ctx, existing.ID); err != nil {
|
||||
return mcp.NewToolResultErrorFromErr("failed to delete document", err), nil
|
||||
}
|
||||
return jsonResult(map[string]any{
|
||||
"deleted": true,
|
||||
"knowledge_id": existing.ID,
|
||||
"title": existing.Title,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
package mcpserver
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// Keep the transport, endpoint guard, handler and shared reader real. Only
|
||||
// storage is replaced, so these tests cover the contract external clients see.
|
||||
type mcpReadChunkRepo struct {
|
||||
interfaces.ChunkRepository
|
||||
chunks []*types.Chunk
|
||||
}
|
||||
|
||||
func (r *mcpReadChunkRepo) ListPagedChunksByKnowledgeID(
|
||||
_ context.Context, tenantID uint64, knowledgeID string, page *types.Pagination, _ []types.ChunkType,
|
||||
_ []string, _ string, _ string, _ string, _ string, _ *bool,
|
||||
) ([]*types.Chunk, int64, error) {
|
||||
if tenantID != 1 || knowledgeID != "doc-1" {
|
||||
return nil, 0, fmt.Errorf("unexpected document scope: %d/%s", tenantID, knowledgeID)
|
||||
}
|
||||
start := min((page.Page-1)*page.PageSize, len(r.chunks))
|
||||
end := min(start+page.PageSize, len(r.chunks))
|
||||
return r.chunks[start:end], int64(len(r.chunks)), nil
|
||||
}
|
||||
|
||||
func (r *mcpReadChunkRepo) ListChunksByParentIDs(context.Context, uint64, []string) ([]*types.Chunk, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
type mcpReadChunkService struct {
|
||||
interfaces.ChunkService
|
||||
repo *mcpReadChunkRepo
|
||||
}
|
||||
|
||||
func (s *mcpReadChunkService) GetRepository() interfaces.ChunkRepository { return s.repo }
|
||||
|
||||
func newMCPReadDocumentEngine(t *testing.T, contents []string) *gin.Engine {
|
||||
t.Helper()
|
||||
kb := &types.KnowledgeBase{ID: "kb-1", TenantID: 1}
|
||||
doc := &types.Knowledge{ID: "doc-1", TenantID: 1, KnowledgeBaseID: kb.ID, Title: "Contract fixture"}
|
||||
repo := &mcpReadChunkRepo{}
|
||||
for i, content := range contents {
|
||||
repo.chunks = append(repo.chunks, &types.Chunk{
|
||||
ID: fmt.Sprintf("chunk-%d", i), TenantID: 1, KnowledgeID: doc.ID, KnowledgeBaseID: kb.ID,
|
||||
// Deliberately sparse: offsets are reading positions, not ChunkIndex values.
|
||||
ChunkIndex: 10 + i*3, ChunkType: types.ChunkTypeText, IsEnabled: true, Content: content,
|
||||
})
|
||||
}
|
||||
srv := NewServer(
|
||||
&stubKBService{kbs: map[string]*types.KnowledgeBase{kb.ID: kb}},
|
||||
&stubKnowledgeService{docs: map[string]*types.Knowledge{doc.ID: doc}},
|
||||
&mcpReadChunkService{repo: repo}, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
|
||||
)
|
||||
ep := &types.MCPEndpoint{
|
||||
ID: "ep-1", TenantID: 1, Enabled: true, KnowledgeBaseIDs: types.StringArray{kb.ID},
|
||||
Tools: types.StringArray{types.MCPEndpointToolReadDocument},
|
||||
}
|
||||
r := gin.New()
|
||||
r.POST("/mcp/:endpoint_id", func(c *gin.Context) {
|
||||
// Authentication is outside this contract test; inject an authenticated
|
||||
// endpoint with the same caller and API-key scope as production.
|
||||
c.Request = c.Request.WithContext(mcpCallContext(1, ep))
|
||||
c.Next()
|
||||
}, gin.WrapH(srv.Handler()))
|
||||
return r
|
||||
}
|
||||
|
||||
type mcpReadDocumentData struct {
|
||||
KnowledgeID string `json:"knowledge_id"`
|
||||
MatchCount int `json:"match_count"`
|
||||
Truncated bool `json:"truncated"`
|
||||
NextOffset *int `json:"next_offset"`
|
||||
Chunks []struct {
|
||||
ID string `json:"chunk_id"`
|
||||
Index int `json:"chunk_index"`
|
||||
Role string `json:"role"`
|
||||
} `json:"chunks"`
|
||||
}
|
||||
|
||||
func callMCPReadDocument(t *testing.T, r *gin.Engine, args map[string]any) mcpReadDocumentData {
|
||||
t.Helper()
|
||||
args["knowledge_id"] = "doc-1"
|
||||
response := rpc(t, r, "tools/call", map[string]any{
|
||||
"name": types.MCPEndpointToolReadDocument, "arguments": args,
|
||||
})
|
||||
require.NotContains(t, response, "error")
|
||||
raw, err := json.Marshal(response["result"])
|
||||
require.NoError(t, err)
|
||||
var result struct {
|
||||
IsError bool `json:"isError"`
|
||||
Content []struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text"`
|
||||
} `json:"content"`
|
||||
Data mcpReadDocumentData `json:"structuredContent"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(raw, &result))
|
||||
require.False(t, result.IsError, "%s", raw)
|
||||
require.Equal(t, "doc-1", result.Data.KnowledgeID)
|
||||
require.Len(t, result.Content, 1)
|
||||
require.Equal(t, "text", result.Content[0].Type)
|
||||
require.Contains(t, result.Content[0].Text, `knowledge_id="doc-1"`)
|
||||
for _, chunk := range result.Data.Chunks {
|
||||
require.Contains(t, result.Content[0].Text, `chunk_id="`+chunk.ID+`"`)
|
||||
}
|
||||
return result.Data
|
||||
}
|
||||
|
||||
func mcpReadChunkIDs(data mcpReadDocumentData, role string) []string {
|
||||
ids := make([]string, 0, len(data.Chunks))
|
||||
for _, chunk := range data.Chunks {
|
||||
if role == "" || chunk.Role == role {
|
||||
ids = append(ids, chunk.ID)
|
||||
}
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
func TestMCPReadDocumentQueryMatchesLiteralTermsInAnyOrder(t *testing.T) {
|
||||
r := newMCPReadDocumentEngine(t, []string{
|
||||
"Before", "beta: build with C++ and ALPHA", "After", "alpha alone", "beta alone", "C only",
|
||||
})
|
||||
for _, query := range []string{"alpha beta", " ALPHA\t\n beta ", "lph et", "C++"} {
|
||||
t.Run(query, func(t *testing.T) {
|
||||
data := callMCPReadDocument(t, r, map[string]any{"query": query, "limit": 1})
|
||||
require.Equal(t, 1, data.MatchCount)
|
||||
require.Equal(t, []string{"chunk-1"}, mcpReadChunkIDs(data, "match"))
|
||||
require.Equal(t, []string{"chunk-0", "chunk-1", "chunk-2"}, mcpReadChunkIDs(data, ""))
|
||||
require.Equal(t, "context_before", data.Chunks[0].Role)
|
||||
require.Equal(t, "context_after", data.Chunks[2].Role)
|
||||
require.False(t, data.Truncated)
|
||||
require.Nil(t, data.NextOffset)
|
||||
})
|
||||
}
|
||||
data := callMCPReadDocument(t, r, map[string]any{"query": "absent"})
|
||||
require.Zero(t, data.MatchCount)
|
||||
require.Empty(t, data.Chunks)
|
||||
require.False(t, data.Truncated)
|
||||
require.Nil(t, data.NextOffset)
|
||||
}
|
||||
|
||||
func TestMCPReadDocumentBlankQueryUsesSequentialPagination(t *testing.T) {
|
||||
r := newMCPReadDocumentEngine(t, []string{"zero", "one", "two", "three", "four"})
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
query any
|
||||
}{
|
||||
{name: "omitted"},
|
||||
{name: "empty", query: ""},
|
||||
{name: "whitespace", query: " \t\n "},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
args := map[string]any{"offset": 1, "limit": 2}
|
||||
if tc.query != nil {
|
||||
args["query"] = tc.query
|
||||
}
|
||||
first := callMCPReadDocument(t, r, args)
|
||||
require.Equal(t, []string{"chunk-1", "chunk-2"}, mcpReadChunkIDs(first, ""))
|
||||
require.Equal(t, 13, first.Chunks[0].Index)
|
||||
require.NotNil(t, first.NextOffset)
|
||||
require.Equal(t, 3, *first.NextOffset)
|
||||
args["offset"] = *first.NextOffset
|
||||
last := callMCPReadDocument(t, r, args)
|
||||
require.Equal(t, []string{"chunk-3", "chunk-4"}, mcpReadChunkIDs(last, ""))
|
||||
require.Nil(t, last.NextOffset)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMCPReadDocumentQueryCapAndContinuationIgnoreLimit(t *testing.T) {
|
||||
contents := make([]string, 44)
|
||||
for i := range contents {
|
||||
contents[i] = "context"
|
||||
if i%2 == 1 {
|
||||
contents[i] = "needle"
|
||||
}
|
||||
}
|
||||
r := newMCPReadDocumentEngine(t, contents)
|
||||
first := callMCPReadDocument(t, r, map[string]any{"query": "needle", "limit": 1})
|
||||
require.Equal(t, 20, first.MatchCount)
|
||||
require.Len(t, first.Chunks, 41, "overlapping contexts are emitted only once per response")
|
||||
require.True(t, first.Truncated)
|
||||
require.NotNil(t, first.NextOffset)
|
||||
require.Equal(t, 41, *first.NextOffset, "resume at the first omitted match's reading position")
|
||||
last := callMCPReadDocument(t, r, map[string]any{
|
||||
"query": "needle", "limit": 1, "offset": *first.NextOffset,
|
||||
})
|
||||
require.Equal(t, 2, last.MatchCount)
|
||||
require.Equal(t, []string{"chunk-40", "chunk-41", "chunk-42", "chunk-43"}, mcpReadChunkIDs(last, ""))
|
||||
require.False(t, last.Truncated)
|
||||
require.Nil(t, last.NextOffset)
|
||||
want := make([]string, 0, 22)
|
||||
for i := 1; i < len(contents); i += 2 {
|
||||
want = append(want, fmt.Sprintf("chunk-%d", i))
|
||||
}
|
||||
require.Equal(t, want, append(mcpReadChunkIDs(first, "match"), mcpReadChunkIDs(last, "match")...))
|
||||
}
|
||||
|
||||
func TestMCPReadDocumentOutputBudgetAllowsCompleteContinuation(t *testing.T) {
|
||||
// Exercise the actual default MCP budget, without injecting an Agent-only
|
||||
// context setting. These chunks exceed it well before the 20-match cap.
|
||||
contents := make([]string, 6)
|
||||
for i := range contents {
|
||||
contents[i] = "needle " + strings.Repeat("body ", 2000)
|
||||
}
|
||||
for _, query := range []string{"", "needle"} {
|
||||
t.Run(fmt.Sprintf("query=%q", query), func(t *testing.T) {
|
||||
r := newMCPReadDocumentEngine(t, contents)
|
||||
offset := 0
|
||||
var seen []string
|
||||
for page := 0; ; page++ {
|
||||
require.Less(t, page, len(contents), "continuation must terminate")
|
||||
data := callMCPReadDocument(t, r, map[string]any{"query": query, "offset": offset, "limit": 20})
|
||||
ids := mcpReadChunkIDs(data, "")
|
||||
if query != "" {
|
||||
ids = mcpReadChunkIDs(data, "match")
|
||||
require.Equal(t, len(ids), data.MatchCount)
|
||||
}
|
||||
require.NotEmpty(t, ids)
|
||||
seen = append(seen, ids...)
|
||||
if page == 0 {
|
||||
require.Less(t, len(ids), len(contents))
|
||||
require.NotNil(t, data.NextOffset)
|
||||
}
|
||||
if data.NextOffset == nil {
|
||||
require.False(t, data.Truncated)
|
||||
break
|
||||
}
|
||||
if query != "" {
|
||||
require.True(t, data.Truncated)
|
||||
}
|
||||
require.Greater(t, *data.NextOffset, offset)
|
||||
offset = *data.NextOffset
|
||||
}
|
||||
require.Equal(t, []string{"chunk-0", "chunk-1", "chunk-2", "chunk-3", "chunk-4", "chunk-5"}, seen)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,402 @@
|
||||
package mcpserver
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"academy/internal/agent/tools"
|
||||
"academy/internal/types"
|
||||
"github.com/mark3labs/mcp-go/mcp"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultListPageSize = 20
|
||||
maxListPageSize = 100
|
||||
defaultChunkLimit = 20
|
||||
maxChunkLimit = 100
|
||||
)
|
||||
|
||||
// readOnlyEndpointAnnotations overrides mcp.NewTool's defaults. Those defaults
|
||||
// set destructiveHint and openWorldHint to true, so a read-only hint alone
|
||||
// still advertises the tool as destructive.
|
||||
func readOnlyEndpointAnnotations() mcp.ToolOption {
|
||||
return func(t *mcp.Tool) {
|
||||
mcp.WithReadOnlyHintAnnotation(true)(t)
|
||||
mcp.WithDestructiveHintAnnotation(false)(t)
|
||||
mcp.WithIdempotentHintAnnotation(true)(t)
|
||||
mcp.WithOpenWorldHintAnnotation(false)(t)
|
||||
}
|
||||
}
|
||||
|
||||
func listKnowledgeBasesTool() mcp.Tool {
|
||||
return mcp.NewTool(types.MCPEndpointToolListKnowledgeBases,
|
||||
mcp.WithDescription("List the knowledge bases this endpoint can access, with their id, name, description "+
|
||||
"and which retrieval modes (semantic, keyword, wiki) each supports. Call this first to learn what is in "+
|
||||
"scope; other tools accept either the id or the exact name."),
|
||||
readOnlyEndpointAnnotations(),
|
||||
)
|
||||
}
|
||||
|
||||
func searchKnowledgeTool() mcp.Tool {
|
||||
return mcp.NewTool(types.MCPEndpointToolSearchKnowledge,
|
||||
mcp.WithDescription("Search the knowledge bases in scope and return the most relevant passages with their "+
|
||||
"document ids and titles. mode hybrid (default) combines semantic and keyword retrieval; semantic "+
|
||||
"ranks by meaning; keyword matches exact terms, identifiers, codes or names."),
|
||||
mcp.WithString("query", mcp.Required(), mcp.Description("A natural-language question, topic, or the exact "+
|
||||
"terms to match")),
|
||||
mcp.WithString("mode", mcp.Description("hybrid (default), semantic, or keyword"),
|
||||
mcp.Enum(tools.SearchModeHybrid, tools.SearchModeSemantic, tools.SearchModeKeyword)),
|
||||
mcp.WithNumber("limit", mcp.Description("Maximum passages to return, default 10, max 30")),
|
||||
mcp.WithArray("knowledge_base_ids", mcp.WithStringItems(),
|
||||
mcp.Description("Optional knowledge base ids or names to restrict the search; defaults to every "+
|
||||
"knowledge base in scope")),
|
||||
readOnlyEndpointAnnotations(),
|
||||
)
|
||||
}
|
||||
|
||||
func grepChunksTool() mcp.Tool {
|
||||
return mcp.NewTool(types.MCPEndpointToolGrepChunks,
|
||||
mcp.WithDescription("Case-insensitive regular-expression search over the text chunks of the knowledge "+
|
||||
"bases in scope. Best for exact terms, identifiers, error codes or product names that semantic search "+
|
||||
"may miss. Candidates come from the keyword index (the semantic index for bases without one) using the "+
|
||||
"literal terms in the pattern, and every returned chunk matches the pattern."),
|
||||
mcp.WithString("query", mcp.Required(), mcp.Description("Regular expression (POSIX, case-insensitive) to "+
|
||||
"match against chunk text; text that is not a valid regular expression is matched literally")),
|
||||
mcp.WithNumber("limit", mcp.Description("Maximum passages to return, default 10, max 30")),
|
||||
mcp.WithArray("knowledge_base_ids", mcp.WithStringItems(),
|
||||
mcp.Description("Optional knowledge base ids or names to restrict the search")),
|
||||
readOnlyEndpointAnnotations(),
|
||||
)
|
||||
}
|
||||
|
||||
func listDocumentsTool() mcp.Tool {
|
||||
return mcp.NewTool(types.MCPEndpointToolListDocuments,
|
||||
mcp.WithDescription("List the documents inside one knowledge base with pagination and an optional title "+
|
||||
"keyword filter. Returns document ids that read_document accepts."),
|
||||
mcp.WithString("knowledge_base_id", mcp.Required(), mcp.Description("Knowledge base id or exact name")),
|
||||
mcp.WithString("keyword", mcp.Description("Optional substring to filter document titles")),
|
||||
mcp.WithNumber("page", mcp.Description("1-based page number, default 1")),
|
||||
mcp.WithNumber("page_size", mcp.Description("Documents per page, default 20, max 100")),
|
||||
readOnlyEndpointAnnotations(),
|
||||
)
|
||||
}
|
||||
|
||||
func readDocumentTool() mcp.Tool {
|
||||
return mcp.NewTool(types.MCPEndpointToolReadDocument,
|
||||
mcp.WithDescription("Read a document's metadata and its text chunks in order. Page through long documents "+
|
||||
"with offset and limit, or pass query to find chunks containing every whitespace-separated word, "+
|
||||
"case-insensitively and in any order. Query mode returns at most 20 matches plus one chunk of "+
|
||||
"context on each side, subject to the output size budget; limit does not apply. If truncated, "+
|
||||
"continue with offset=next_offset from the response."),
|
||||
mcp.WithString("knowledge_id", mcp.Required(),
|
||||
mcp.Description("Document id from search results or list_documents")),
|
||||
mcp.WithNumber("offset", mcp.Description("0-based position in document reading order, default 0; "+
|
||||
"use returned next_offset to continue")),
|
||||
mcp.WithNumber("limit", mcp.Description("Chunks per page without query, default 20, max 100; "+
|
||||
"ignored in query mode; output size budget may reduce the page")),
|
||||
mcp.WithString("query", mcp.Description("Optional case-insensitive keywords split on whitespace; "+
|
||||
"every word must occur in the chunk, in any order (not an exact phrase)")),
|
||||
readOnlyEndpointAnnotations(),
|
||||
)
|
||||
}
|
||||
|
||||
type knowledgeBaseSummary struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Type string `json:"type"`
|
||||
Capabilities []string `json:"capabilities"`
|
||||
}
|
||||
|
||||
func summarizeKnowledgeBase(kb *types.KnowledgeBase) knowledgeBaseSummary {
|
||||
caps := []string{}
|
||||
if kb.IsVectorEnabled() {
|
||||
caps = append(caps, "semantic")
|
||||
}
|
||||
if kb.IsKeywordEnabled() {
|
||||
caps = append(caps, "keyword")
|
||||
}
|
||||
if kb.IsWikiEnabled() {
|
||||
caps = append(caps, "wiki")
|
||||
}
|
||||
return knowledgeBaseSummary{
|
||||
ID: kb.ID,
|
||||
Name: kb.Name,
|
||||
Description: kb.Description,
|
||||
Type: kb.Type,
|
||||
Capabilities: caps,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) handleListKnowledgeBases(ctx context.Context, _ mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
ep, err := endpointFromContext(ctx)
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("unauthorized"), nil
|
||||
}
|
||||
kbs, err := s.allowedKnowledgeBases(ctx, ep)
|
||||
if err != nil {
|
||||
return mcp.NewToolResultErrorFromErr("failed to list knowledge bases", err), nil
|
||||
}
|
||||
out := make([]knowledgeBaseSummary, 0, len(kbs))
|
||||
for _, kb := range kbs {
|
||||
out = append(out, summarizeKnowledgeBase(kb))
|
||||
}
|
||||
return jsonResult(map[string]any{"knowledge_bases": out, "total": len(out)})
|
||||
}
|
||||
|
||||
func (s *Server) handleSearchKnowledge(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
ep, err := endpointFromContext(ctx)
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("unauthorized"), nil
|
||||
}
|
||||
query, err := req.RequireString("query")
|
||||
if err != nil || strings.TrimSpace(query) == "" {
|
||||
return mcp.NewToolResultError("query is required"), nil
|
||||
}
|
||||
kbs, err := s.selectKnowledgeBases(ctx, ep, req.GetStringSlice("knowledge_base_ids", nil))
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError(err.Error()), nil
|
||||
}
|
||||
kbs = retrievableKnowledgeBases(kbs)
|
||||
if len(kbs) == 0 {
|
||||
return mcp.NewToolResultError(
|
||||
"none of the selected knowledge bases supports semantic or keyword retrieval"), nil
|
||||
}
|
||||
return s.runSearchKnowledge(ctx, kbs, strings.TrimSpace(query),
|
||||
req.GetString("mode", tools.SearchModeHybrid), req.GetInt("limit", 0))
|
||||
}
|
||||
|
||||
// runSearchKnowledge executes the shared search_knowledge agent tool for
|
||||
// both the search_knowledge and grep_chunks endpoint tools.
|
||||
func (s *Server) runSearchKnowledge(
|
||||
ctx context.Context, kbs []*types.KnowledgeBase, query, mode string, limit int,
|
||||
) (*mcp.CallToolResult, error) {
|
||||
return s.runSearchKnowledgeWithFilter(ctx, kbs, query, mode, limit, nil)
|
||||
}
|
||||
|
||||
func (s *Server) runSearchKnowledgeWithFilter(
|
||||
ctx context.Context, kbs []*types.KnowledgeBase, query, mode string, limit int, pattern *regexp.Regexp,
|
||||
) (*mcp.CallToolResult, error) {
|
||||
tool := tools.NewSearchKnowledgeTool(
|
||||
s.kbService, s.knowledgeService, s.chunkService, searchTargetsFor(kbs), nil, s.cfg,
|
||||
)
|
||||
if pattern != nil {
|
||||
tool.WithPatternFilter(pattern)
|
||||
}
|
||||
callArgs := map[string]any{
|
||||
"query": query,
|
||||
"mode": mode,
|
||||
"knowledge_base_ids": knowledgeBaseIDs(kbs),
|
||||
}
|
||||
if limit > 0 {
|
||||
callArgs["limit"] = limit
|
||||
}
|
||||
args, _ := json.Marshal(callArgs)
|
||||
res, execErr := tool.Execute(ctx, args)
|
||||
return toolResultFromAgentTool(res, execErr), nil
|
||||
}
|
||||
|
||||
func (s *Server) handleGrepChunks(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
ep, err := endpointFromContext(ctx)
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("unauthorized"), nil
|
||||
}
|
||||
query, err := req.RequireString("query")
|
||||
if err != nil || strings.TrimSpace(query) == "" {
|
||||
return mcp.NewToolResultError("query is required"), nil
|
||||
}
|
||||
kbs, err := s.selectKnowledgeBases(ctx, ep, req.GetStringSlice("knowledge_base_ids", nil))
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError(err.Error()), nil
|
||||
}
|
||||
kbs = retrievableKnowledgeBases(kbs)
|
||||
if len(kbs) == 0 {
|
||||
return mcp.NewToolResultError(
|
||||
"none of the selected knowledge bases has a chunk index (vector or keyword)"), nil
|
||||
}
|
||||
pattern, terms := grepPatternAndTerms(strings.TrimSpace(query))
|
||||
if terms == "" {
|
||||
return mcp.NewToolResultError("the pattern contains no literal text to look up; include at least one " +
|
||||
"word, identifier or phrase (for example \"timeout|deadline\" instead of \"^\\d+$\")"), nil
|
||||
}
|
||||
return s.runSearchKnowledgeWithFilter(
|
||||
ctx, kbs, terms, tools.SearchModeKeyword, req.GetInt("limit", 0), pattern,
|
||||
)
|
||||
}
|
||||
|
||||
var grepEscapeRE = regexp.MustCompile(`\\[A-Za-z]`)
|
||||
|
||||
// grepPatternAndTerms keeps grep_chunks' regular-expression contract on top
|
||||
// of index-backed retrieval. The pattern compiles case-insensitively (text
|
||||
// that is not a valid expression is escaped and matched literally, as it
|
||||
// would have failed in the database before). The literal runs inside the
|
||||
// pattern become the keyword query that fetches candidates; results are then
|
||||
// verified against the pattern itself.
|
||||
func grepPatternAndTerms(query string) (*regexp.Regexp, string) {
|
||||
re, err := regexp.Compile("(?i)" + query)
|
||||
source := query
|
||||
if err != nil {
|
||||
re = regexp.MustCompile("(?i)" + regexp.QuoteMeta(query))
|
||||
} else {
|
||||
// Escapes such as \d, \b or \s carry no literal text.
|
||||
source = grepEscapeRE.ReplaceAllString(query, " ")
|
||||
}
|
||||
fields := strings.FieldsFunc(source, func(r rune) bool {
|
||||
return !unicode.IsLetter(r) && !unicode.IsDigit(r) && r != '_' && r != '-'
|
||||
})
|
||||
seen := make(map[string]bool, len(fields))
|
||||
terms := make([]string, 0, len(fields))
|
||||
for _, f := range fields {
|
||||
key := strings.ToLower(f)
|
||||
if seen[key] {
|
||||
continue
|
||||
}
|
||||
seen[key] = true
|
||||
terms = append(terms, f)
|
||||
}
|
||||
return re, strings.Join(terms, " ")
|
||||
}
|
||||
|
||||
type documentSummary struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
FileName string `json:"file_name,omitempty"`
|
||||
FileType string `json:"file_type,omitempty"`
|
||||
Source string `json:"source,omitempty"`
|
||||
ParseStatus string `json:"parse_status"`
|
||||
Description string `json:"description,omitempty"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
}
|
||||
|
||||
func summarizeKnowledge(k *types.Knowledge) documentSummary {
|
||||
return documentSummary{
|
||||
ID: k.ID,
|
||||
Title: k.Title,
|
||||
FileName: k.FileName,
|
||||
FileType: k.FileType,
|
||||
Source: k.Source,
|
||||
ParseStatus: k.ParseStatus,
|
||||
Description: k.Description,
|
||||
CreatedAt: k.CreatedAt.Format("2006-01-02T15:04:05Z07:00"),
|
||||
UpdatedAt: k.UpdatedAt.Format("2006-01-02T15:04:05Z07:00"),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) handleListDocuments(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
ep, err := endpointFromContext(ctx)
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("unauthorized"), nil
|
||||
}
|
||||
selector, err := req.RequireString("knowledge_base_id")
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("knowledge_base_id is required"), nil
|
||||
}
|
||||
kbs, err := s.selectKnowledgeBases(ctx, ep, []string{selector})
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError(err.Error()), nil
|
||||
}
|
||||
kb := kbs[0]
|
||||
// Documents live under the knowledge base owner; run the listing there.
|
||||
ctx, err = s.scopedKBContext(ctx, kb, types.OrgRoleViewer)
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError(err.Error()), nil
|
||||
}
|
||||
page := req.GetInt("page", 1)
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
pageSize := req.GetInt("page_size", defaultListPageSize)
|
||||
if pageSize < 1 {
|
||||
pageSize = defaultListPageSize
|
||||
}
|
||||
if pageSize > maxListPageSize {
|
||||
pageSize = maxListPageSize
|
||||
}
|
||||
result, err := s.knowledgeService.ListPagedKnowledgeByKnowledgeBaseID(
|
||||
ctx, kb.ID,
|
||||
&types.Pagination{Page: page, PageSize: pageSize},
|
||||
types.KnowledgeListFilter{Keyword: strings.TrimSpace(req.GetString("keyword", ""))},
|
||||
)
|
||||
if err != nil {
|
||||
return mcp.NewToolResultErrorFromErr("failed to list documents", err), nil
|
||||
}
|
||||
docs := []documentSummary{}
|
||||
if rows, ok := result.Data.([]*types.Knowledge); ok {
|
||||
for _, k := range rows {
|
||||
docs = append(docs, summarizeKnowledge(k))
|
||||
}
|
||||
}
|
||||
return jsonResult(map[string]any{
|
||||
"knowledge_base_id": kb.ID,
|
||||
"total": result.Total,
|
||||
"page": result.Page,
|
||||
"page_size": result.PageSize,
|
||||
"documents": docs,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleReadDocument(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
ep, err := endpointFromContext(ctx)
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("unauthorized"), nil
|
||||
}
|
||||
knowledgeID, err := req.RequireString("knowledge_id")
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("knowledge_id is required"), nil
|
||||
}
|
||||
k, kb, err := s.knowledgeInScope(ctx, ep, knowledgeID)
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError(err.Error()), nil
|
||||
}
|
||||
ctx, err = s.scopedKBContext(ctx, kb, types.OrgRoleViewer)
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError(err.Error()), nil
|
||||
}
|
||||
limit := req.GetInt("limit", defaultChunkLimit)
|
||||
if limit < 1 {
|
||||
limit = defaultChunkLimit
|
||||
}
|
||||
if limit > maxChunkLimit {
|
||||
limit = maxChunkLimit
|
||||
}
|
||||
offset := req.GetInt("offset", 0)
|
||||
if offset < 0 {
|
||||
offset = 0
|
||||
}
|
||||
tool := tools.NewReadDocumentTool(
|
||||
s.knowledgeService, s.chunkService, searchTargetsFor([]*types.KnowledgeBase{kb}),
|
||||
)
|
||||
callArgs := map[string]any{
|
||||
"id": k.ID,
|
||||
"limit": limit,
|
||||
"offset": offset,
|
||||
}
|
||||
if query := strings.TrimSpace(req.GetString("query", "")); query != "" {
|
||||
callArgs["query"] = query
|
||||
}
|
||||
args, _ := json.Marshal(callArgs)
|
||||
res, execErr := tool.Execute(ctx, args)
|
||||
if execErr != nil || res == nil || !res.Success {
|
||||
return toolResultFromAgentTool(res, execErr), nil
|
||||
}
|
||||
if res.Data == nil {
|
||||
res.Data = map[string]interface{}{}
|
||||
}
|
||||
res.Data["document"] = summarizeKnowledge(k)
|
||||
res.Data["knowledge_base"] = map[string]any{"id": kb.ID, "name": kb.Name}
|
||||
return toolResultFromAgentTool(res, nil), nil
|
||||
}
|
||||
|
||||
// jsonResult renders structured data both as text (for clients that only
|
||||
// read content) and as structuredContent.
|
||||
func jsonResult(v any) (*mcp.CallToolResult, error) {
|
||||
raw, err := json.MarshalIndent(v, "", " ")
|
||||
if err != nil {
|
||||
return mcp.NewToolResultErrorFromErr("failed to encode result", err), nil
|
||||
}
|
||||
return mcp.NewToolResultStructured(v, string(raw)), nil
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
package mcpserver
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
|
||||
"academy/internal/agent/tools"
|
||||
"academy/internal/types"
|
||||
"github.com/mark3labs/mcp-go/mcp"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultWikiSearchLimit = 10
|
||||
maxWikiSearchLimit = 50
|
||||
defaultWikiIndexLimit = 50
|
||||
maxWikiIndexLimit = 200
|
||||
)
|
||||
|
||||
func wikiSearchTool() mcp.Tool {
|
||||
return mcp.NewTool(types.MCPEndpointToolWikiSearch,
|
||||
mcp.WithDescription("Search the generated wiki pages of the knowledge bases in scope by title, alias and "+
|
||||
"content. Returns page slugs that wiki_read_page accepts. Only knowledge bases with a wiki are "+
|
||||
"searched."),
|
||||
mcp.WithString("query", mcp.Required(), mcp.Description("Search terms or a regular expression "+
|
||||
"(case-insensitive POSIX); text that is not a valid regular expression is matched literally")),
|
||||
mcp.WithBoolean("regex", mcp.Description("false forces a literal match; true requires a valid regular "+
|
||||
"expression; omit for the default behaviour")),
|
||||
mcp.WithArray("knowledge_base_ids", mcp.WithStringItems(),
|
||||
mcp.Description("Optional knowledge base ids or names to restrict the search")),
|
||||
mcp.WithNumber("limit", mcp.Description("Maximum pages to return, default 10, max 50")),
|
||||
readOnlyEndpointAnnotations(),
|
||||
)
|
||||
}
|
||||
|
||||
func wikiReadPageTool() mcp.Tool {
|
||||
return mcp.NewTool(types.MCPEndpointToolWikiReadPage,
|
||||
mcp.WithDescription("Read one wiki page by slug, including its content and outgoing links."),
|
||||
mcp.WithString("slug", mcp.Required(), mcp.Description("Page slug from wiki_search or wiki_index, e.g. "+
|
||||
"concept/rag")),
|
||||
mcp.WithString("knowledge_base_id", mcp.Description("Knowledge base id or name, required only when the same "+
|
||||
"slug exists in several wikis")),
|
||||
readOnlyEndpointAnnotations(),
|
||||
)
|
||||
}
|
||||
|
||||
func wikiIndexTool() mcp.Tool {
|
||||
return mcp.NewTool(types.MCPEndpointToolWikiIndex,
|
||||
mcp.WithDescription("Browse the table of contents of one knowledge base's wiki: the intro plus pages "+
|
||||
"grouped by type (summary, entity, concept, ...)."),
|
||||
mcp.WithString("knowledge_base_id", mcp.Required(), mcp.Description("Knowledge base id or exact name")),
|
||||
mcp.WithNumber("limit", mcp.Description("Maximum entries per page type, default 50, max 200")),
|
||||
readOnlyEndpointAnnotations(),
|
||||
)
|
||||
}
|
||||
|
||||
func (s *Server) wikiScopeFromRequest(
|
||||
ctx context.Context, ep *types.MCPEndpoint, requested []string,
|
||||
) ([]*types.KnowledgeBase, error) {
|
||||
kbs, err := s.selectKnowledgeBases(ctx, ep, requested)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
kbs = wikiKnowledgeBases(kbs)
|
||||
if len(kbs) == 0 {
|
||||
return nil, errNoWikiInScope
|
||||
}
|
||||
return kbs, nil
|
||||
}
|
||||
|
||||
var errNoWikiInScope = &toolError{"none of the selected knowledge bases has a wiki; call list_knowledge_bases and " +
|
||||
"pick one whose capabilities include \"wiki\""}
|
||||
|
||||
type toolError struct{ msg string }
|
||||
|
||||
func (e *toolError) Error() string { return e.msg }
|
||||
|
||||
// withOutputInData keeps the wiki page body available to MCP clients that
|
||||
// only inspect structuredContent. Other tools retain their existing payload
|
||||
// shape because this compatibility field is only needed by the wiki tools.
|
||||
func withOutputInData(res *types.ToolResult) *types.ToolResult {
|
||||
if res == nil || !res.Success || res.Output == "" {
|
||||
return res
|
||||
}
|
||||
if res.Data == nil {
|
||||
res.Data = map[string]interface{}{}
|
||||
}
|
||||
if _, exists := res.Data["content"]; !exists {
|
||||
res.Data["content"] = res.Output
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func (s *Server) handleWikiSearch(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
ep, err := endpointFromContext(ctx)
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("unauthorized"), nil
|
||||
}
|
||||
query, err := req.RequireString("query")
|
||||
if err != nil || strings.TrimSpace(query) == "" {
|
||||
return mcp.NewToolResultError("query is required"), nil
|
||||
}
|
||||
kbs, err := s.wikiScopeFromRequest(ctx, ep, req.GetStringSlice("knowledge_base_ids", nil))
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError(err.Error()), nil
|
||||
}
|
||||
limit := req.GetInt("limit", defaultWikiSearchLimit)
|
||||
if limit < 1 {
|
||||
limit = defaultWikiSearchLimit
|
||||
}
|
||||
if limit > maxWikiSearchLimit {
|
||||
limit = maxWikiSearchLimit
|
||||
}
|
||||
tool := tools.NewWikiSearchTool(s.wikiService, s.knowledgeService, wikiScopesFor(kbs), tools.NewWikiRouteResolver())
|
||||
callArgs := map[string]any{
|
||||
"query": strings.TrimSpace(query),
|
||||
"limit": limit,
|
||||
}
|
||||
// Only forward regex when the client set it, so the default keeps the
|
||||
// endpoint's historical regular-expression semantics.
|
||||
if v, ok := req.GetArguments()["regex"].(bool); ok {
|
||||
callArgs["regex"] = v
|
||||
}
|
||||
args, _ := json.Marshal(callArgs)
|
||||
res, execErr := tool.Execute(ctx, args)
|
||||
return toolResultFromAgentTool(withOutputInData(res), execErr), nil
|
||||
}
|
||||
|
||||
func (s *Server) handleWikiReadPage(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
ep, err := endpointFromContext(ctx)
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("unauthorized"), nil
|
||||
}
|
||||
slug, err := req.RequireString("slug")
|
||||
if err != nil || strings.TrimSpace(slug) == "" {
|
||||
return mcp.NewToolResultError("slug is required"), nil
|
||||
}
|
||||
var requested []string
|
||||
if kbSel := strings.TrimSpace(req.GetString("knowledge_base_id", "")); kbSel != "" {
|
||||
requested = []string{kbSel}
|
||||
}
|
||||
kbs, err := s.wikiScopeFromRequest(ctx, ep, requested)
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError(err.Error()), nil
|
||||
}
|
||||
tool := tools.NewWikiReadPageTool(
|
||||
s.wikiService, s.knowledgeService, wikiScopesFor(kbs), tools.NewWikiRouteResolver(),
|
||||
)
|
||||
args, _ := json.Marshal(map[string]any{"slug": strings.TrimSpace(slug)})
|
||||
res, execErr := tool.Execute(ctx, args)
|
||||
return toolResultFromAgentTool(withOutputInData(res), execErr), nil
|
||||
}
|
||||
|
||||
func (s *Server) handleWikiIndex(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
ep, err := endpointFromContext(ctx)
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("unauthorized"), nil
|
||||
}
|
||||
selector, err := req.RequireString("knowledge_base_id")
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("knowledge_base_id is required"), nil
|
||||
}
|
||||
kbs, err := s.wikiScopeFromRequest(ctx, ep, []string{selector})
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError(err.Error()), nil
|
||||
}
|
||||
limit := req.GetInt("limit", defaultWikiIndexLimit)
|
||||
if limit < 1 {
|
||||
limit = defaultWikiIndexLimit
|
||||
}
|
||||
if limit > maxWikiIndexLimit {
|
||||
limit = maxWikiIndexLimit
|
||||
}
|
||||
view, err := s.wikiService.GetIndexView(ctx, kbs[0].ID, nil, limit, "")
|
||||
if err != nil {
|
||||
return mcp.NewToolResultErrorFromErr("failed to load wiki index", err), nil
|
||||
}
|
||||
return jsonResult(map[string]any{
|
||||
"knowledge_base_id": kbs[0].ID,
|
||||
"intro": view.Intro,
|
||||
"groups": view.Groups,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package mcpserver
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/mark3labs/mcp-go/mcp"
|
||||
)
|
||||
|
||||
func TestWithOutputInDataAddsWikiContent(t *testing.T) {
|
||||
const output = "<page slug=\"concept/example\">Page body</page>"
|
||||
result := withOutputInData(&types.ToolResult{
|
||||
Success: true,
|
||||
Output: output,
|
||||
Data: map[string]interface{}{"found_kbs": map[string][]string{"concept/example": {"kb-1"}}},
|
||||
})
|
||||
|
||||
if got := result.Data["content"]; got != output {
|
||||
t.Fatalf("content = %v, want %q", got, output)
|
||||
}
|
||||
if got := result.Data["found_kbs"]; got == nil {
|
||||
t.Fatal("withOutputInData removed existing structured data")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWithOutputInDataInitializesStructuredData(t *testing.T) {
|
||||
const output = "page body"
|
||||
result := withOutputInData(&types.ToolResult{Success: true, Output: output})
|
||||
|
||||
if result.Data == nil {
|
||||
t.Fatal("withOutputInData left structured data nil")
|
||||
}
|
||||
if got := result.Data["content"]; got != output {
|
||||
t.Fatalf("content = %v, want %q", got, output)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWithOutputInDataDoesNotOverwriteExistingContent(t *testing.T) {
|
||||
const existing = "already structured"
|
||||
result := withOutputInData(&types.ToolResult{
|
||||
Success: true,
|
||||
Output: "human-readable output",
|
||||
Data: map[string]interface{}{"content": existing},
|
||||
})
|
||||
|
||||
if got := result.Data["content"]; got != existing {
|
||||
t.Fatalf("content = %v, want %q", got, existing)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWithOutputInDataLeavesNonSuccessfulResultsUnchanged(t *testing.T) {
|
||||
failed := &types.ToolResult{Output: "failure output", Data: map[string]interface{}{}}
|
||||
if got := withOutputInData(failed); got != failed {
|
||||
t.Fatal("non-successful result was replaced")
|
||||
}
|
||||
if _, exists := failed.Data["content"]; exists {
|
||||
t.Fatal("non-successful result received structured content")
|
||||
}
|
||||
|
||||
empty := &types.ToolResult{Success: true, Data: map[string]interface{}{}}
|
||||
if got := withOutputInData(empty); got != empty {
|
||||
t.Fatal("empty-output result was replaced")
|
||||
}
|
||||
if _, exists := empty.Data["content"]; exists {
|
||||
t.Fatal("empty-output result received structured content")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWikiResultIncludesOutputInStructuredContent(t *testing.T) {
|
||||
const output = "<page slug=\"concept/example\">Page body</page>"
|
||||
result := toolResultFromAgentTool(withOutputInData(&types.ToolResult{
|
||||
Success: true,
|
||||
Output: output,
|
||||
Data: map[string]interface{}{"found_kbs": map[string][]string{"concept/example": {"kb-1"}}},
|
||||
}), nil)
|
||||
|
||||
structured, ok := result.StructuredContent.(map[string]interface{})
|
||||
if !ok {
|
||||
t.Fatalf("structured content has type %T, want map[string]interface{}", result.StructuredContent)
|
||||
}
|
||||
if got := structured["content"]; got != output {
|
||||
t.Fatalf("structured content = %v, want %q", got, output)
|
||||
}
|
||||
|
||||
if len(result.Content) != 1 {
|
||||
t.Fatalf("content blocks = %d, want 1", len(result.Content))
|
||||
}
|
||||
text, ok := result.Content[0].(mcp.TextContent)
|
||||
if !ok {
|
||||
t.Fatalf("content block has type %T, want mcp.TextContent", result.Content[0])
|
||||
}
|
||||
if text.Text != output {
|
||||
t.Fatalf("text content = %q, want %q", text.Text, output)
|
||||
}
|
||||
|
||||
wire, err := json.Marshal(result)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal MCP result: %v", err)
|
||||
}
|
||||
var payload struct {
|
||||
Content []map[string]interface{} `json:"content"`
|
||||
StructuredContent map[string]interface{} `json:"structuredContent"`
|
||||
}
|
||||
if err := json.Unmarshal(wire, &payload); err != nil {
|
||||
t.Fatalf("unmarshal MCP result: %v", err)
|
||||
}
|
||||
if got := payload.StructuredContent["content"]; got != output {
|
||||
t.Fatalf("wire structured content = %v, want %q", got, output)
|
||||
}
|
||||
if len(payload.Content) != 1 || payload.Content[0]["text"] != output {
|
||||
t.Fatalf("wire text content = %v, want %q", payload.Content, output)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenericToolResultDoesNotGainWikiContent(t *testing.T) {
|
||||
result := toolResultFromAgentTool(&types.ToolResult{
|
||||
Success: true,
|
||||
Output: "document output",
|
||||
Data: map[string]interface{}{"document": "structured document"},
|
||||
}, nil)
|
||||
|
||||
structured, ok := result.StructuredContent.(map[string]interface{})
|
||||
if !ok {
|
||||
t.Fatalf("structured content has type %T, want map[string]interface{}", result.StructuredContent)
|
||||
}
|
||||
if _, exists := structured["content"]; exists {
|
||||
t.Fatal("generic tool result unexpectedly gained wiki content")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user