Files
Docwell/Server/internal/ai/mcp.go
T
tajniak81andClaude Opus 5.5 78b7710090 Add AI chat, writing actions, workspace embeddings and an MCP server
Phase E of the AFFiNE parity plan (ADR-15):

- internal/ai: OpenAI-compatible, Anthropic (official Go SDK) and Ollama
  drivers; BYOK profiles per workspace and for the instance, with keys
  encrypted by DOCWELL_SECRET_KEY, failover order, a test call and usage
  counters.
- Embeddings: an indexer that follows PocketBase like the search index,
  chunks pages along their blocks and keeps vectors in a bbolt file in
  the data dir (no cgo); progress, ignored pages and extra files.
- Chat sessions scoped to a page, space or workspace, streamed as
  server-sent events, with citations to pages and blocks, fork and
  history; retrieval only from pages the asker can read.
- Writing actions (rewrite, fix, shorter, longer, summarise, translate,
  continue, custom) in the editor's selection toolbar.
- POST /mcp: MCP over Streamable HTTP with personal API tokens; read
  tokens search and read pages, write tokens also create and update them.
- Web app chat panel (Ctrl+J), workspace AI settings, an admin AI page,
  OpenAPI, generated clients, migration and translations.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 21:58:22 +01:00

413 lines
13 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
package ai
import (
"context"
"encoding/json"
"fmt"
"slices"
"strings"
"docwell/server/internal/access"
"docwell/server/internal/apperr"
"docwell/server/internal/directory"
)
// ---- MCP server --------------------------------------------------------------------
//
// POST /mcp speaks the Model Context Protocol over Streamable HTTP: one
// JSON-RPC 2.0 message (or batch) per request, answered with JSON. The
// caller is an API token's owner; write tokens also get the write tools.
// MCPVersions are the protocol versions this server speaks, newest first.
var MCPVersions = []string{"2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"}
type rpcRequest struct {
JSONRPC string `json:"jsonrpc"`
ID json.RawMessage `json:"id,omitempty"`
Method string `json:"method"`
Params json.RawMessage `json:"params,omitempty"`
}
type rpcError struct {
Code int `json:"code"`
Message string `json:"message"`
}
type rpcResponse struct {
JSONRPC string `json:"jsonrpc"`
ID json.RawMessage `json:"id"`
Result any `json:"result,omitempty"`
Error *rpcError `json:"error,omitempty"`
}
type mcpTool struct {
Name string `json:"name"`
Title string `json:"title,omitempty"`
Description string `json:"description"`
InputSchema map[string]any `json:"inputSchema"`
Annotations map[string]any `json:"annotations,omitempty"`
write bool
}
func schema(required []string, props map[string]any) map[string]any {
if required == nil {
required = []string{}
}
return map[string]any{"type": "object", "properties": props, "required": required, "additionalProperties": false}
}
func str(desc string) map[string]any { return map[string]any{"type": "string", "description": desc} }
var readOnly = map[string]any{"readOnlyHint": true, "openWorldHint": false}
var mcpTools = []mcpTool{
{
Name: "list_workspaces", Title: "List workspaces", Annotations: readOnly,
Description: "Lists the Docwell workspaces you can open, with their ids.",
InputSchema: schema(nil, map[string]any{}),
},
{
Name: "list_spaces", Title: "List spaces", Annotations: readOnly,
Description: "Lists the spaces of a workspace you can open, with their ids.",
InputSchema: schema([]string{"workspace"}, map[string]any{"workspace": str("Workspace id")}),
},
{
Name: "list_pages", Title: "List pages", Annotations: readOnly,
Description: "Lists the page tree of a space (id, parent, title), or with only a workspace, its most recently changed pages.",
InputSchema: schema(nil, map[string]any{"workspace": str("Workspace id (recent pages)"), "space": str("Space id (the whole tree)")}),
},
{
Name: "search", Title: "Search pages", Annotations: readOnly,
Description: "Full-text search over the pages of a workspace. Returns page ids, titles and snippets.",
InputSchema: schema([]string{"workspace", "query"}, map[string]any{
"workspace": str("Workspace id"), "query": str("Words to look for"), "space": str("Optional space id to search in"),
"limit": map[string]any{"type": "integer", "minimum": 1, "maximum": 50, "description": "Most results (default 10)"},
}),
},
{
Name: "read_page", Title: "Read a page", Annotations: readOnly,
Description: "Returns a page's title and body as Markdown.",
InputSchema: schema([]string{"page"}, map[string]any{"page": str("Page id")}),
},
{
Name: "ask", Title: "Ask the workspace", Annotations: map[string]any{"readOnlyHint": true, "openWorldHint": true},
Description: "Asks the workspace's AI a question; it answers from the pages you can read, with numbered sources. Needs AI set up in the workspace.",
InputSchema: schema([]string{"workspace", "question"}, map[string]any{
"workspace": str("Workspace id"), "question": str("The question"),
"space": str("Optional space id to limit the sources"), "page": str("Optional page id to ask about"),
}),
},
{
Name: "create_page", Title: "Create a page", write: true,
Annotations: map[string]any{"readOnlyHint": false, "destructiveHint": false, "openWorldHint": false},
Description: "Creates a page in a space from Markdown and returns its id.",
InputSchema: schema([]string{"space", "title"}, map[string]any{
"space": str("Space id"), "title": str("Page title"), "markdown": str("Page body as Markdown"),
"parent": str("Optional parent page id"),
}),
},
{
Name: "update_page", Title: "Update a page", write: true,
Annotations: map[string]any{"readOnlyHint": false, "destructiveHint": true, "openWorldHint": false},
Description: "Replaces a page's body with Markdown, or appends Markdown to it (mode \"append\"). Page history keeps the previous version.",
InputSchema: schema([]string{"page", "markdown"}, map[string]any{
"page": str("Page id"), "markdown": str("Markdown"),
"mode": map[string]any{"type": "string", "enum": []string{"replace", "append"}, "description": "replace (default) or append"},
}),
},
}
// MCP answers one HTTP request body. It returns nil for a message that
// needs no answer (notifications), which the transport turns into 202.
// onWrite (optional) hears about every successful write tool call.
func (s *Service) MCP(ctx context.Context, c access.Caller, canWrite bool, body []byte, onWrite func(tool, page string)) ([]byte, error) {
ctx = context.WithValue(ctx, onWriteKey{}, onWrite)
trimmed := strings.TrimSpace(string(body))
if strings.HasPrefix(trimmed, "[") {
var batch []rpcRequest
if err := json.Unmarshal(body, &batch); err != nil {
return json.Marshal(rpcResponse{JSONRPC: "2.0", ID: json.RawMessage("null"), Error: &rpcError{-32700, "parse error"}})
}
var out []rpcResponse
for _, req := range batch {
if res, ok := s.mcpOne(ctx, c, canWrite, req); ok {
out = append(out, res)
}
}
if len(out) == 0 {
return nil, nil
}
return json.Marshal(out)
}
var req rpcRequest
if err := json.Unmarshal(body, &req); err != nil {
return json.Marshal(rpcResponse{JSONRPC: "2.0", ID: json.RawMessage("null"), Error: &rpcError{-32700, "parse error"}})
}
res, ok := s.mcpOne(ctx, c, canWrite, req)
if !ok {
return nil, nil
}
return json.Marshal(res)
}
func (s *Service) mcpOne(ctx context.Context, c access.Caller, canWrite bool, req rpcRequest) (rpcResponse, bool) {
if len(req.ID) == 0 {
return rpcResponse{}, false // a notification (initialized, cancelled …)
}
res := rpcResponse{JSONRPC: "2.0", ID: req.ID}
switch req.Method {
case "initialize":
var p struct {
ProtocolVersion string `json:"protocolVersion"`
}
_ = json.Unmarshal(req.Params, &p)
version := MCPVersions[0]
if slices.Contains(MCPVersions, p.ProtocolVersion) {
version = p.ProtocolVersion
}
instructions := "Docwell is a team wiki. Use list_workspaces first, then search or list_pages to find pages and read_page to read them."
if canWrite {
instructions += " create_page and update_page change pages as the token's owner."
}
res.Result = map[string]any{
"protocolVersion": version,
"capabilities": map[string]any{"tools": map[string]any{"listChanged": false}},
"serverInfo": map[string]string{"name": "docwell", "title": "Docwell", "version": "1"},
"instructions": instructions,
}
case "ping":
res.Result = map[string]any{}
case "tools/list":
tools := []mcpTool{}
for _, t := range mcpTools {
if !t.write || canWrite {
tools = append(tools, t)
}
}
res.Result = map[string]any{"tools": tools}
case "tools/call":
var p struct {
Name string `json:"name"`
Arguments map[string]any `json:"arguments"`
}
if err := json.Unmarshal(req.Params, &p); err != nil {
res.Error = &rpcError{-32602, "invalid params"}
break
}
i := slices.IndexFunc(mcpTools, func(t mcpTool) bool { return t.Name == p.Name })
if i < 0 || (mcpTools[i].write && !canWrite) {
res.Error = &rpcError{-32602, "unknown tool: " + p.Name}
break
}
text, err := s.callTool(ctx, c, p.Name, args(p.Arguments))
if err != nil {
msg := err.Error()
if e, ok := apperr.As(err); ok {
msg = e.Message
for f, m := range e.Fields {
msg += fmt.Sprintf(" (%s: %s)", f, m)
}
}
res.Result = map[string]any{"content": []map[string]string{{"type": "text", "text": msg}}, "isError": true}
break
}
res.Result = map[string]any{"content": []map[string]string{{"type": "text", "text": text}}}
case "resources/list":
res.Result = map[string]any{"resources": []any{}}
case "prompts/list":
res.Result = map[string]any{"prompts": []any{}}
default:
res.Error = &rpcError{-32601, "method not found: " + req.Method}
}
return res, true
}
type onWriteKey struct{}
func wrote(ctx context.Context, tool, page string) {
if fn, _ := ctx.Value(onWriteKey{}).(func(tool, page string)); fn != nil {
fn(tool, page)
}
}
type args map[string]any
func (a args) str(k string) string {
v, _ := a[k].(string)
return strings.TrimSpace(v)
}
func (a args) need(k string) (string, error) {
if v := a.str(k); v != "" {
return v, nil
}
return "", apperr.Invalid("missing argument: " + k)
}
func toJSON(v any) (string, error) {
b, err := json.MarshalIndent(v, "", " ")
return string(b), err
}
func (s *Service) callTool(ctx context.Context, c access.Caller, name string, a args) (string, error) {
switch name {
case "list_workspaces":
list, err := s.dir.ListWorkspaces(ctx, c)
if err != nil {
return "", err
}
type ws struct{ ID, Name, Role string }
out := []ws{}
for _, w := range list {
out = append(out, ws{w.ID, w.Name, w.Role})
}
return toJSON(out)
case "list_spaces":
wsID, err := a.need("workspace")
if err != nil {
return "", err
}
list, err := s.dir.ListSpaces(ctx, c, wsID)
if err != nil {
return "", err
}
type sp struct{ ID, Name, Description, Role string }
out := []sp{}
for _, x := range list {
out = append(out, sp{x.ID, x.Name, x.Description, x.Role})
}
return toJSON(out)
case "list_pages":
if space := a.str("space"); space != "" {
nodes, err := s.dir.ListPages(ctx, c, space)
if err != nil {
return "", err
}
type pg struct{ ID, Parent, Title string }
out := []pg{}
for _, n := range nodes {
out = append(out, pg{n.ID, n.Parent, n.Title})
}
return toJSON(out)
}
wsID, err := a.need("workspace")
if err != nil {
return "", apperr.Invalid("give a space, or a workspace for its recent pages")
}
list, err := s.dir.RecentPages(ctx, c, wsID, "", 50)
if err != nil {
return "", err
}
return toJSON(list)
case "search":
wsID, err := a.need("workspace")
if err != nil {
return "", err
}
q, err := a.need("query")
if err != nil {
return "", err
}
limit := 10
if f, ok := a["limit"].(float64); ok {
limit = min(max(int(f), 1), 50)
}
res, err := s.dir.Search(ctx, c, wsID, directory.SearchQuery{Text: q, Space: a.str("space"), Limit: limit})
if err != nil {
return "", err
}
type hit struct {
Page string `json:"page"`
Title string `json:"title"`
Space string `json:"space"`
Snippet string `json:"snippet"`
Updated string `json:"updated"`
}
out := []hit{}
for _, h := range res.Items {
out = append(out, hit{h.ID, h.Title, h.SpaceName, h.Snippet, h.Updated})
}
return toJSON(map[string]any{"total": res.Total, "results": out})
case "read_page":
id, err := a.need("page")
if err != nil {
return "", err
}
p, err := s.dir.ReadPage(ctx, c, id)
if err != nil {
return "", err
}
return fmt.Sprintf("# %s\n\n<!-- page %s, space %s, updated %s -->\n\n%s", p.Title, p.ID, p.Space, p.Updated, p.Markdown), nil
case "ask":
wsID, err := a.need("workspace")
if err != nil {
return "", err
}
q, err := a.need("question")
if err != nil {
return "", err
}
scope, scopeID := ScopeWorkspace, ""
if p := a.str("page"); p != "" {
scope, scopeID = ScopePage, p
} else if sp := a.str("space"); sp != "" {
scope, scopeID = ScopeSpace, sp
}
answer, cites, err := s.Answer(ctx, c, wsID, scope, scopeID, q)
if err != nil {
return "", err
}
var b strings.Builder
b.WriteString(answer)
if len(cites) > 0 {
b.WriteString("\n\nSources:\n")
for _, ct := range cites {
ref := "page " + ct.Page
if ct.File != "" {
ref = "file"
}
fmt.Fprintf(&b, "[%d] %s (%s)\n", ct.N, ct.Title, ref)
}
}
return b.String(), nil
case "create_page":
space, err := a.need("space")
if err != nil {
return "", err
}
title, err := a.need("title")
if err != nil {
return "", err
}
p, err := s.dir.CreatePage(ctx, c, space, directory.CreatePageInput{Title: title, Parent: a.str("parent")})
if err != nil {
return "", err
}
if md := a.str("markdown"); md != "" {
if _, err := s.dir.WriteMarkdown(ctx, c, p.ID, md, false); err != nil {
return "", err
}
}
wrote(ctx, name, p.ID)
return toJSON(map[string]string{"page": p.ID, "title": p.Title, "space": p.Space})
case "update_page":
id, err := a.need("page")
if err != nil {
return "", err
}
md, err := a.need("markdown")
if err != nil {
return "", err
}
p, err := s.dir.WriteMarkdown(ctx, c, id, md, a.str("mode") == "append")
if err != nil {
return "", err
}
wrote(ctx, name, p.ID)
return toJSON(map[string]string{"page": p.ID, "title": p.Title, "updated": p.Updated})
}
return "", apperr.Invalid("unknown tool")
}