package wikijs import ( "bytes" "context" "encoding/json" "errors" "fmt" "io" "log/slog" "net/http" "net/url" "strings" "time" ) // maxResponseBytes bounds the response body read from WikiJS. const maxResponseBytes = 32 << 20 // Client talks to the WikiJS GraphQL API. type Client struct { baseURL string endpoint string apiKey string userAgent string http *http.Client logger *slog.Logger } // Option customizes a [Client]. type Option func(*Client) // WithHTTPClient sets the HTTP client used for GraphQL requests. func WithHTTPClient(hc *http.Client) Option { return func(c *Client) { if hc != nil { c.http = hc } } } // WithLogger enables debug logging of GraphQL operations. func WithLogger(logger *slog.Logger) Option { return func(c *Client) { if logger != nil { c.logger = logger } } } // WithUserAgent overrides the User-Agent sent to WikiJS. func WithUserAgent(userAgent string) Option { return func(c *Client) { if userAgent != "" { c.userAgent = userAgent } } } // New creates a client for a WikiJS base URL. The URL may end with /graphql; // it is normalized so that the GraphQL endpoint is always addressed once. func New(rawBaseURL, apiKey string, opts ...Option) (*Client, error) { base := strings.TrimRight(strings.TrimSpace(rawBaseURL), "/") u, err := url.Parse(base) if err != nil { return nil, fmt.Errorf("parse WikiJS URL: %w", err) } if (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" { return nil, fmt.Errorf("WikiJS URL must be an absolute http(s) URL, got %q", rawBaseURL) } if u.RawQuery != "" || u.Fragment != "" { return nil, fmt.Errorf("WikiJS URL must not contain a query or fragment, got %q", rawBaseURL) } endpoint := base if strings.HasSuffix(base, "/graphql") { base = strings.TrimSuffix(base, "/graphql") } else { endpoint += "/graphql" } c := &Client{ baseURL: base, endpoint: endpoint, apiKey: apiKey, userAgent: "wikijs-mcp", http: http.DefaultClient, logger: slog.New(slog.DiscardHandler), } for _, opt := range opts { opt(c) } return c, nil } // SearchPages runs a WikiJS full-text search. path and locale are optional. func (c *Client) SearchPages(ctx context.Context, query, path, locale string) (SearchResults, error) { vars := map[string]any{"query": query} putString(vars, "path", path) putString(vars, "locale", locale) var data struct { Pages *struct { Search *struct { Results []*SearchHit `json:"results"` Suggestions []string `json:"suggestions"` TotalHits int `json:"totalHits"` } `json:"search"` } `json:"pages"` } if err := c.do(ctx, "SearchPages", searchPagesQuery, vars, &data); err != nil { return SearchResults{}, err } out := SearchResults{Results: []SearchHit{}, Suggestions: []string{}} if data.Pages == nil || data.Pages.Search == nil { return out, nil } for _, hit := range data.Pages.Search.Results { if hit == nil { continue } hit.URL = c.pageURL(hit.Path, hit.Locale) out.Results = append(out.Results, *hit) } out.Suggestions = append(out.Suggestions, data.Pages.Search.Suggestions...) out.TotalHits = data.Pages.Search.TotalHits return out, nil } // PageByID returns a page by its numeric ID. It returns a nil page without an // error when WikiJS does not know the ID. func (c *Client) PageByID(ctx context.Context, id int) (*Page, error) { var data struct { Pages *struct { Single *Page `json:"single"` } `json:"pages"` } if err := c.do(ctx, "GetPageById", pageByIDQuery, map[string]any{"id": id}, &data); err != nil { return nil, err } if data.Pages == nil || data.Pages.Single == nil { return nil, nil } return c.decorate(data.Pages.Single), nil } // PageByPath returns a page by its path and locale. It returns a nil page // without an error when the page does not exist. func (c *Client) PageByPath(ctx context.Context, path, locale string) (*Page, error) { vars := map[string]any{"path": path, "locale": locale} var data struct { Pages *struct { Single *Page `json:"singleByPath"` } `json:"pages"` } if err := c.do(ctx, "GetPageByPath", pageByPathQuery, vars, &data); err != nil { return nil, err } if data.Pages == nil || data.Pages.Single == nil { return nil, nil } return c.decorate(data.Pages.Single), nil } // ListPages returns pages, optionally filtered by limit, locale, and tags. func (c *Client) ListPages(ctx context.Context, opts ListOptions) ([]PageListItem, error) { vars := map[string]any{} if opts.Limit != nil { vars["limit"] = *opts.Limit } putString(vars, "locale", opts.Locale) if len(opts.Tags) > 0 { vars["tags"] = opts.Tags } var data struct { Pages *struct { List []*PageListItem `json:"list"` } `json:"pages"` } if err := c.do(ctx, "GetAllPages", listPagesQuery, vars, &data); err != nil { return nil, err } out := []PageListItem{} if data.Pages == nil { return out, nil } for _, page := range data.Pages.List { if page == nil { continue } page.URL = c.pageURL(page.Path, page.Locale) if page.Tags == nil { page.Tags = []string{} } out = append(out, *page) } return out, nil } // CreatePage creates a page. func (c *Client) CreatePage(ctx context.Context, in CreatePageInput) (MutationResult, error) { vars := map[string]any{ "title": in.Title, "content": in.Content, "description": in.Description, "editor": in.Editor, "isPublished": in.IsPublished, "isPrivate": in.IsPrivate, "locale": in.Locale, "tags": nonNilStrings(in.Tags), "path": in.Path, } var data struct { Pages *struct { Create *struct { ResponseResult *responseResult `json:"responseResult"` } `json:"create"` } `json:"pages"` } if err := c.do(ctx, "CreatePage", createPageMutation, vars, &data); err != nil { return MutationResult{}, err } if data.Pages == nil || data.Pages.Create == nil { return MutationResult{}, errors.New("wikijs CreatePage: missing create result") } return mutationResult(data.Pages.Create.ResponseResult) } // UpdatePage updates a page. func (c *Client) UpdatePage(ctx context.Context, in UpdatePageInput) (MutationResult, error) { vars := map[string]any{ "id": in.ID, "title": in.Title, "content": in.Content, "description": in.Description, "editor": in.Editor, "isPublished": in.IsPublished, "isPrivate": in.IsPrivate, "locale": in.Locale, "tags": nonNilStrings(in.Tags), "path": in.Path, } var data struct { Pages *struct { Update *struct { ResponseResult *responseResult `json:"responseResult"` } `json:"update"` } `json:"pages"` } if err := c.do(ctx, "UpdatePage", updatePageMutation, vars, &data); err != nil { return MutationResult{}, err } if data.Pages == nil || data.Pages.Update == nil { return MutationResult{}, errors.New("wikijs UpdatePage: missing update result") } return mutationResult(data.Pages.Update.ResponseResult) } type responseResult struct { Succeeded bool `json:"succeeded"` ErrorCode int `json:"errorCode"` Slug string `json:"slug"` Message string `json:"message"` } func mutationResult(rr *responseResult) (MutationResult, error) { if rr == nil { return MutationResult{}, errors.New("wikijs mutation: missing responseResult") } return MutationResult{ Succeeded: rr.Succeeded, Message: rr.Message, ErrorCode: rr.ErrorCode, Slug: rr.Slug, }, nil } type graphqlRequest struct { Query string `json:"query"` Variables map[string]any `json:"variables,omitempty"` } type graphqlError struct { Message string `json:"message"` } type graphqlResponse struct { Data json.RawMessage `json:"data"` Errors []graphqlError `json:"errors"` } // APIError describes a failed WikiJS request. type APIError struct { Operation string Status int Messages []string Body string Err error } func (e *APIError) Error() string { var b strings.Builder b.WriteString("wikijs") if e.Operation != "" { b.WriteByte(' ') b.WriteString(e.Operation) } b.WriteString(": ") switch { case len(e.Messages) > 0: b.WriteString(strings.Join(e.Messages, "; ")) case e.Body != "": b.WriteString(e.Body) case e.Err != nil: b.WriteString(e.Err.Error()) default: b.WriteString("request failed") } if e.Status != 0 { fmt.Fprintf(&b, " (HTTP %d)", e.Status) } return b.String() } func (e *APIError) Unwrap() error { return e.Err } func (c *Client) do(ctx context.Context, operation, query string, vars map[string]any, out any) error { payload, err := json.Marshal(graphqlRequest{Query: query, Variables: vars}) if err != nil { return fmt.Errorf("wikijs %s: encode request: %w", operation, err) } req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.endpoint, bytes.NewReader(payload)) if err != nil { return fmt.Errorf("wikijs %s: build request: %w", operation, err) } req.Header.Set("Content-Type", "application/json") req.Header.Set("Accept", "application/json") req.Header.Set("Authorization", "Bearer "+c.apiKey) req.Header.Set("User-Agent", c.userAgent) start := time.Now() resp, err := c.http.Do(req) if err != nil { return fmt.Errorf("wikijs %s: %w", operation, err) } defer resp.Body.Close() body, err := io.ReadAll(io.LimitReader(resp.Body, maxResponseBytes+1)) if err != nil { return fmt.Errorf("wikijs %s: read response: %w", operation, err) } if len(body) > maxResponseBytes { return fmt.Errorf("wikijs %s: response exceeds %d bytes", operation, maxResponseBytes) } if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices { return &APIError{ Operation: operation, Status: resp.StatusCode, Body: truncate(strings.TrimSpace(string(body)), 512), } } var envelope graphqlResponse if err := json.Unmarshal(body, &envelope); err != nil { return &APIError{Operation: operation, Err: fmt.Errorf("decode response: %w", err)} } if len(envelope.Errors) > 0 { messages := make([]string, 0, len(envelope.Errors)) for _, e := range envelope.Errors { messages = append(messages, e.Message) } return &APIError{Operation: operation, Messages: messages} } if len(envelope.Data) == 0 || string(envelope.Data) == "null" { return &APIError{Operation: operation, Messages: []string{"response contains no data"}} } if err := json.Unmarshal(envelope.Data, out); err != nil { return fmt.Errorf("wikijs %s: decode data: %w", operation, err) } c.logger.Debug("wikijs request", "operation", operation, "duration", time.Since(start), "status", resp.StatusCode, ) return nil } func (c *Client) decorate(page *Page) *Page { page.URL = c.pageURL(page.Path, page.Locale) if page.Tags == nil { page.Tags = []Tag{} } return page } func (c *Client) pageURL(path, locale string) string { p := strings.TrimLeft(path, "/") if locale != "" && locale != "en" { return c.baseURL + "/" + locale + "/" + p } return c.baseURL + "/" + p } func putString(vars map[string]any, key, value string) { if value != "" { vars[key] = value } } func nonNilStrings(values []string) []string { if values == nil { return []string{} } return values } func truncate(s string, max int) string { if len(s) <= max { return s } return s[:max] + "..." }