fix(handler): /knowledge/search · accept ?query= and reject empty keyword

Silent-failure footgun in SearchKnowledge handler:

  keyword := c.Query("keyword")   // only "keyword" recognized
  // empty keyword → service falls back to default listing (created_at DESC)
  // → caller sees "all queries return the same N newest knowledges"

This is exactly what happened to a downstream agent (Support GPT) — it was
sending ?query=... (the parameter name every MCP / semantic-search tool
uses) and getting a constant 5-card listing back regardless of input. The
caller diagnosed it as "WeKnora embedding has degraded · vector channel
returns constant rankings", but actually the parameter was never read, the
search service got keyword="", and the SQL came back as a plain
list-by-created_at.

The handler stays a filename/title LIKE search (its real purpose is the
document-management UI). Two tweaks:

1. Accept ?query= as an alias for ?keyword= · this is what MCP / agent
   integrations actually send. Cheap compatibility win, zero downside.
2. Empty keyword/query → 400 with a clear hint. Refusing the request is
   strictly better than silently returning a default listing that looks
   like "search results" but isn't query-driven.

Separately worth noting: callers who actually want semantic recall should
use POST /api/v1/knowledge-bases/{kb_id}/hybrid-search · which is the
real vector + BM25 endpoint. This handler was never the right tool for
RAG queries · the silent failure just made it look like one.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
toy0116
2026-06-05 08:01:02 +08:00
committed by lyingbug
parent e2a41ecf0a
commit e76210a695
+12
View File
@@ -1793,7 +1793,19 @@ func (h *KnowledgeHandler) SearchKnowledge(c *gin.Context) {
if userID, ok := c.Get(types.UserIDContextKey.String()); ok {
ctx = context.WithValue(ctx, types.UserIDContextKey, userID)
}
// Accept both ?keyword= (legacy / upstream name) and ?query= (what most
// MCP / agent integrations send). Falling silently back to an unsorted
// listing when both are empty caused the "all queries return the same 5
// newest cards" footgun — return 400 instead so the caller gets a clear
// signal that the search wasn't query-driven.
keyword := c.Query("keyword")
if keyword == "" {
keyword = c.Query("query")
}
if strings.TrimSpace(keyword) == "" {
c.Error(errors.NewBadRequestError("missing search keyword: pass ?keyword=... or ?query=..."))
return
}
offset, _ := strconv.Atoi(c.DefaultQuery("offset", "0"))
limit, _ := strconv.Atoi(c.DefaultQuery("limit", "20"))