WeKnora/internal/mcpserver/scope.go

223 lines
7.6 KiB
Go
Raw Normal View History

feat(mcp): add built-in MCP server with per-workspace endpoints (#3371) * feat(mcp): add built-in MCP server with per-workspace endpoints WeKnora previously exposed itself to MCP clients only through the Python package under mcp-server/, which binds one process to one API key and therefore to one workspace, and mirrors the REST API tool-for-tool. This adds a native MCP server surface to the Go backend: - New mcp_endpoints table (PostgreSQL 000100, SQLite 000020). A workspace can publish any number of endpoints, each with its own bearer token (SHA-256 stored, rotatable, shown once), knowledge-base allowlist, tool allowlist, default agent and per-minute rate limit. - Management API under /api/v1/mcp-endpoints (Viewer reads, Admin writes, API keys need manage_channels) plus a tool catalog endpoint. - internal/mcpserver hosts one mcp-go Streamable HTTP server in stateless mode at /mcp/:endpoint_id. tools/list is filtered per endpoint and tools/call re-checks the allowlist, applies rate limiting and touches last_used_at. MCPEndpointAuth resolves the token and injects the workspace, an mcp_endpoint principal and an API-key style scope derived from the endpoint, so existing knowledge-base and capability checks apply unchanged. - Redesigned tool set (12 tools in four groups): retrieval and reading reuse the agent's native tools; ask runs the default or a named agent synchronously and returns a cited answer with a session_id for follow-ups; wiki tools cover search, read and index; write tools are off by default. Knowledge bases accept ids or names. - Frontend: new "MCP Server" integrations tab (tab id mcpserver, to avoid clashing with the existing MCP-client settings section) with endpoint cards, a create/edit drawer, a one-time token dialog and ready-to-paste snippets for Cursor/VS Code/Claude Desktop, Claude Code and mcp-remote. Locales updated in all five languages. - Deployment capability integrations.mcpserver wired on both sides. - Docs: website-docs MCP page now leads with the built-in server; the Python mcp-server README carries a deprecation notice. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(mcp): wire the MCP server into DI/router and tighten authorization The previous commit lost eight staged files to the repo pre-commit hook, which resolves ROOT to the main checkout and re-adds the main-checkout copies of tracked files into the worktree index. This commit restores them (container providers, RouterParams and route registration, context key, principal, clone table entry, deployment capability key, SQLite parity test) and addresses the review findings: - Knowledge-base scope is authorized, not trusted: endpoint allowlists and every tool call resolve each knowledge base through access.ResolveKB for the calling principal (ownership or organization share). Foreign IDs are rejected on create/update and dropped at call time. - Write tools mint explicit editor grants via access.KBAccess.WithGrant before calling the knowledge service, so add/update/delete go through the same RequireKBWrite path as the REST API. add_document also checks the grant itself. - ask no longer accepts agent_id. It runs only the endpoint's configured agent; tenant-owned agents and user-facing builtins qualify, internal builtins (wiki fixer, skill installer) are refused both on save and at call time. Web search is forced off for MCP calls. - Tool annotations match behaviour: ask is not read-only, add_document is a mutation. - CORS allows MCP-Protocol-Version / Mcp-Session-Id / Last-Event-ID and exposes Mcp-Session-Id for browser-based MCP clients. - Rate limiter runs its local cleanup goroutine; SQLite migration gains the deleted_at index for parity with PostgreSQL; non-ASCII endpoint names get unique mcpServers keys derived from the endpoint id. - Swagger annotations on the management handler. - Tests: KB isolation (service and server), write grants, endpoint-agent restriction, tool annotations, and a router test that mounts the public /mcp/:endpoint_id surface and checks the deployment capability. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * chore(mcp): renumber migrations after rebase onto main main took 000100 / 000020 for chunks_index_diet, so the mcp_endpoints migrations move to 000101 (PostgreSQL) and 000021 (SQLite); the SQLite parity test and docs follow. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(mcp): run document tools under the knowledge base owner tenant Shared knowledge bases resolved through access.ResolveKB were only half usable: documents of an organization-shared knowledge base are stored under the owner tenant, so the document-level tools that queried by the calling tenant found nothing, and add_document would have created rows under the caller's tenant inside someone else's knowledge base. - knowledgeInScope loads documents tenant-agnostically and then requires the document to belong to an allowed knowledge base and to that base's tenant. - scopedKBContext replaces grantContext: it resolves the grant, switches the execution tenant to the knowledge base owner (KBAccess.Context) and swaps TenantInfo to the owner so storage/model settings resolve there. list_documents, read_document and every write tool run under it. - Locale text and docs no longer claim clients can pass agent_id. - Go SDK gains MCP endpoint methods (client/mcp_endpoint.go) with docs, and the Swagger artifacts are regenerated. - Tests: shared knowledge base read/write under the owner tenant, spoofed document tenant rejected, viewer share cannot write. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * chore(mcp): renumber migrations after rebase onto main main now carries 000101 / 000021 (knowledge_profiles), so the mcp_endpoints migrations move to 000102 (PostgreSQL) and 000022 (SQLite); the SQLite parity test expects version 22 and the docs follow. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(mcp): guard last_used touch without a repository and wrap SDK line The transport tests build the server without a repository; the background last_used_at write then dereferenced a nil interface and, on the slower CI runner, took the test binary down. touchLastUsed now returns early when no repository is wired, and the tests inject a recording repository and assert the touch instead. Also wraps a 123-column SDK signature for the client module's lll check. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-17 14:40:05 +00:00
package mcpserver
import (
"context"
"errors"
"fmt"
"strings"
"github.com/Tencent/WeKnora/internal/agent/tools"
"github.com/Tencent/WeKnora/internal/application/access"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/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) {
grant, err := s.resolveKB(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
}
scoped := grant.Context(ctx)
caller := types.CallerFromContext(ctx)
if kb.TenantID != caller.TenantID && s.tenantService != nil {
owner, err := s.tenantService.GetTenantByID(ctx, kb.TenantID)
if err != nil || owner == nil {
return ctx, fmt.Errorf("the workspace owning knowledge base %q is unavailable", kb.ID)
}
scoped = context.WithValue(scoped, types.TenantInfoContextKey, owner)
}
return 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
}