WeKnora/internal/mcpserver/server.go

236 lines
8.1 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 hosts WeKnora'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"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/ratelimit"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/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 = "weknora"
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
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,
) *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,
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 = "WeKnora 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)
return next(ctx, req)
}
}
// 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)
}