feat(cli): --format / NDJSON / chat & agent invoke / MCP / SetAgentHelp / signal-aware ctx / kb create --storage-provider

Adds the structured-output and agent-help surface plus root-level signal
handling so AI agents (and humans working through pipes) get a stable
wire contract.

* --format text|json|ndjson flag, registered per-command on outputs that
  need it; default text on TTY, json on pipe. --jq <expr> pairs with json
  / ndjson to filter or project. FormatOptions absorbs JQ; WantsJSON()
  helper for the JSON dispatch.
* WriteNDJSON helper in internal/format/ (per ndjson.org: one JSON value
  per line, arrays split element-per-line, empty slice → zero bytes).
* chat / agent invoke wire --format ndjson via SDK StreamResponse /
  AgentStreamResponse 1:1 passthrough. Both commands detect ctx.Cancelled
  in every stream + session-create path and emit a stable
  "operation.cancelled" code on Ctrl-C / SIGTERM.
* main.go wires signal.NotifyContext(SIGINT, SIGTERM) into the root
  context so long-running commands run their cancellation cleanup
  (re-emit auto-created session id, etc); the process exits 130 when
  the context was signal-cancelled, matching Unix convention.
* MCP chat / agent_invoke output schemas extended with thinking /
  tool_calls / assistant_message_id (server-side accumulated; MCP
  tools/call has no standard partial-response). doc_view and doc_download
  now use doc_id (not knowledge_id) so agents see a single id naming
  convention across all tools — matches the chunk_list / search_chunks
  schemas and the CLI's <doc-id> positional.
* SetAgentHelp(cmd, AgentHelp{...}) — opt-in machine-friendly --help
  payload activated by WEKNORA_AGENT_HELP=1. Applied to chat / kb list.
* kb create --storage-provider <local|minio|cos|tos|s3|oss|ks3> — sets
  the new KB's storage_provider_config.provider at creation time (server
  does not expose it on update). Required on self-hosted deployments
  where the server-side default doesn't pre-populate a provider —
  without it, subsequent doc upload returns a misleading "kb not found".
This commit is contained in:
nullkey
2026-05-18 01:37:47 +08:00
committed by lyingbug
parent 5deffbd769
commit 567d7ac74e
18 changed files with 983 additions and 475 deletions
+26 -18
View File
@@ -196,7 +196,7 @@ func addDocList(server *mcpsdk.Server, svc knowledgeService) {
// ---- doc_view ------------------------------------------------------------
type docViewInput struct {
KnowledgeID string `json:"knowledge_id" jsonschema:"document (knowledge entry) ID"`
DocID string `json:"doc_id" jsonschema:"document ID (same value as the doc-id positional in CLI commands)"`
}
func addDocView(server *mcpsdk.Server, svc knowledgeService) {
@@ -204,10 +204,10 @@ func addDocView(server *mcpsdk.Server, svc knowledgeService) {
Name: "doc_view",
Description: "Fetch a single document by ID. Returns the Knowledge record (file_name, title, type, parse_status, size, embedding_model_id, source URL if any, etc.).",
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, in docViewInput) (*mcpsdk.CallToolResult, *sdk.Knowledge, error) {
if in.KnowledgeID == "" {
return nil, nil, fmt.Errorf("knowledge_id is required")
if in.DocID == "" {
return nil, nil, fmt.Errorf("doc_id is required")
}
k, err := svc.GetKnowledge(ctx, in.KnowledgeID)
k, err := svc.GetKnowledge(ctx, in.DocID)
if err != nil {
return nil, nil, fmt.Errorf("get knowledge: %w", err)
}
@@ -218,13 +218,13 @@ func addDocView(server *mcpsdk.Server, svc knowledgeService) {
// ---- doc_download --------------------------------------------------------
type docDownloadInput struct {
KnowledgeID string `json:"knowledge_id" jsonschema:"document (knowledge entry) ID"`
DocID string `json:"doc_id" jsonschema:"document ID (same value as the doc-id positional in CLI commands)"`
}
type docDownloadOutput struct {
KnowledgeID string `json:"knowledge_id"`
FileName string `json:"file_name"`
Bytes int `json:"bytes"`
DocID string `json:"doc_id"`
FileName string `json:"file_name"`
Bytes int `json:"bytes"`
// Content is the file contents (UTF-8 if text, base64 if the SDK
// reports a binary-looking blob). For binary, agents should decode
// before consuming.
@@ -243,10 +243,10 @@ func addDocDownload(server *mcpsdk.Server, svc knowledgeService) {
Name: "doc_download",
Description: "Download a document's raw bytes by ID. Capped at 1 MiB per call - for larger documents, use search_chunks to find the relevant excerpts. is_base64 reports whether content was base64-encoded (heuristic: presence of NUL byte in the first 512 bytes).",
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, in docDownloadInput) (*mcpsdk.CallToolResult, docDownloadOutput, error) {
if in.KnowledgeID == "" {
return nil, docDownloadOutput{}, fmt.Errorf("knowledge_id is required")
if in.DocID == "" {
return nil, docDownloadOutput{}, fmt.Errorf("doc_id is required")
}
name, body, err := svc.OpenKnowledgeFile(ctx, in.KnowledgeID)
name, body, err := svc.OpenKnowledgeFile(ctx, in.DocID)
if err != nil {
return nil, docDownloadOutput{}, fmt.Errorf("open knowledge file: %w", err)
}
@@ -260,11 +260,11 @@ func addDocDownload(server *mcpsdk.Server, svc knowledgeService) {
}
content, isBase64 := encodeDownload(buf)
return nil, docDownloadOutput{
KnowledgeID: in.KnowledgeID,
FileName: name,
Bytes: len(buf),
Content: content,
IsBase64: isBase64,
DocID: in.DocID,
FileName: name,
Bytes: len(buf),
Content: content,
IsBase64: isBase64,
}, nil
})
}
@@ -338,14 +338,17 @@ type chatInput struct {
type chatOutput struct {
Answer string `json:"answer"`
References []*sdk.SearchResult `json:"references"`
Thinking string `json:"thinking,omitempty"` // reasoning text from response_type=thinking; empty for non-reasoning models
SessionID string `json:"session_id"`
AssistantMessageID string `json:"assistant_message_id,omitempty"`
KBID string `json:"kb_id"`
Query string `json:"query"`
}
func addChat(server *mcpsdk.Server, svc chatService) {
mcpsdk.AddTool(server, &mcpsdk.Tool{
Name: "chat",
Description: "Stream a RAG answer from the LLM, grounded in the given knowledge base. The SSE stream is accumulated server-side; this tool returns the full answer + references + session_id once the stream completes. Pass session_id to continue a multi-turn conversation; otherwise a fresh session is auto-created.",
Description: "Stream a RAG answer from the LLM, grounded in the given knowledge base. The SSE stream is accumulated server-side (MCP tools/call has no standard partial-response, so this is NOT streaming); the tool returns the full accumulated response once the stream completes. Pass session_id to continue a multi-turn conversation; otherwise a fresh session is auto-created.",
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, in chatInput) (*mcpsdk.CallToolResult, any, error) {
if in.KBID == "" {
return nil, nil, fmt.Errorf("kb_id is required")
@@ -385,8 +388,11 @@ func addChat(server *mcpsdk.Server, svc chatService) {
return nil, chatOutput{
Answer: acc.Result(),
References: acc.References,
Thinking: acc.Thinking(),
SessionID: sid,
AssistantMessageID: acc.AssistantMessageID,
KBID: in.KBID,
Query: in.Query,
}, nil
})
}
@@ -430,12 +436,13 @@ type agentInvokeOutput struct {
Thinking string `json:"thinking,omitempty"`
SessionID string `json:"session_id"`
AgentID string `json:"agent_id"`
Query string `json:"query"`
}
func addAgentInvoke(server *mcpsdk.Server, svc agentInvokeService) {
mcpsdk.AddTool(server, &mcpsdk.Tool{
Name: "agent_invoke",
Description: "Run a query through a custom agent (system prompt + tool allow-list + KB scope). The agent's SSE stream is accumulated server-side; this tool returns the final answer plus the trace (references, tool_events, thinking).",
Description: "Run a query through a custom agent (system prompt + tool allow-list + KB scope). The agent's SSE stream is accumulated server-side (MCP tools/call has no standard partial-response, so this is NOT streaming); the tool returns the final accumulated response once the stream completes.",
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, in agentInvokeInput) (*mcpsdk.CallToolResult, any, error) {
if in.AgentID == "" {
return nil, nil, fmt.Errorf("agent_id is required")
@@ -477,6 +484,7 @@ func addAgentInvoke(server *mcpsdk.Server, svc agentInvokeService) {
Thinking: acc.Thinking(),
SessionID: sessionID,
AgentID: in.AgentID,
Query: in.Query,
}, nil
})
}
+51 -3
View File
@@ -326,7 +326,7 @@ func TestTool_DocView(t *testing.T) {
svc := &fakeSvc{getDoc: &sdk.Knowledge{ID: "k1", FileName: "a.pdf"}}
c, _ := newTestServer(t, svc)
var out sdk.Knowledge
callTool(t, c, "doc_view", map[string]any{"knowledge_id": "k1"}, &out)
callTool(t, c, "doc_view", map[string]any{"doc_id": "k1"}, &out)
if out.ID != "k1" {
t.Errorf("got %+v", out)
}
@@ -339,7 +339,7 @@ func TestTool_DocDownload_Text(t *testing.T) {
}
c, _ := newTestServer(t, svc)
var out docDownloadOutput
callTool(t, c, "doc_download", map[string]any{"knowledge_id": "k1"}, &out)
callTool(t, c, "doc_download", map[string]any{"doc_id": "k1"}, &out)
if out.Content != "hello world" {
t.Errorf("content = %q", out.Content)
}
@@ -357,7 +357,7 @@ func TestTool_DocDownload_BinaryBase64(t *testing.T) {
}
c, _ := newTestServer(t, svc)
var out docDownloadOutput
callTool(t, c, "doc_download", map[string]any{"knowledge_id": "k1"}, &out)
callTool(t, c, "doc_download", map[string]any{"doc_id": "k1"}, &out)
if !out.IsBase64 {
t.Errorf("binary should be base64; got is_base64=%v content=%q", out.IsBase64, out.Content)
}
@@ -423,6 +423,54 @@ func TestTool_Chat_AccumulateAnswerAndReferences(t *testing.T) {
}
}
func TestMCP_ChatToolReturnsThinking(t *testing.T) {
svc := &fakeSvc{
kbStreamEvents: []*sdk.StreamResponse{
{ResponseType: sdk.ResponseTypeThinking, Content: "let me reason..."},
{ResponseType: sdk.ResponseTypeAnswer, Content: "final answer"},
{ResponseType: sdk.ResponseTypeComplete},
},
}
c, _ := newTestServer(t, svc)
var out chatOutput
callTool(t, c, "chat", map[string]any{"kb_id": "kb_x", "query": "deep question"}, &out)
if out.Thinking != "let me reason..." {
t.Errorf("thinking = %q, want %q", out.Thinking, "let me reason...")
}
if out.Answer != "final answer" {
t.Errorf("answer = %q, want %q", out.Answer, "final answer")
}
if out.KBID != "kb_x" {
t.Errorf("kb_id = %q, want %q", out.KBID, "kb_x")
}
if out.Query != "deep question" {
t.Errorf("query = %q, want %q", out.Query, "deep question")
}
}
func TestMCP_AgentInvokeToolReturnsToolCalls(t *testing.T) {
svc := &fakeSvc{
agentEvents: []*sdk.AgentStreamResponse{
{ResponseType: sdk.AgentResponseTypeThinking, Content: "agent thinks"},
{ResponseType: sdk.AgentResponseTypeToolCall, ID: "tc1", Content: "knowledge_search"},
{ResponseType: sdk.AgentResponseTypeAnswer, Content: "agent answer"},
{Done: true},
},
}
c, _ := newTestServer(t, svc)
var out agentInvokeOutput
callTool(t, c, "agent_invoke", map[string]any{"agent_id": "ag1", "query": "tool question"}, &out)
if out.Thinking != "agent thinks" {
t.Errorf("thinking = %q, want %q", out.Thinking, "agent thinks")
}
if len(out.ToolEvents) != 1 || out.ToolEvents[0].ID != "tc1" {
t.Errorf("tool_events = %+v, want 1 event with id tc1", out.ToolEvents)
}
if out.Query != "tool question" {
t.Errorf("query = %q, want %q", out.Query, "tool question")
}
}
func TestTool_Chat_ExistingSessionSkipsCreate(t *testing.T) {
svc := &fakeSvc{
kbStreamEvents: []*sdk.StreamResponse{{ResponseType: sdk.ResponseTypeComplete}},