refactor(cli): envelope sweep — Emit shape, batch ops, MCP StructuredContent, api flag cleanup

Sweep every CLI output path through the v0.7 envelope contract.

FormatOptions.Emit signature changes to (w, data, meta *output.Meta)
so list commands surface meta.count / has_more in the wire envelope.
TTY indent decision plumbed via FormatOptions.TTY (set by
ResolveDefault). --format and --jq promoted to persistent root flags
so unknown-subcommand paths still reach the typed-envelope guard
(per-command registration would have rejected --format on unknown
commands as cobra-prose exit 2). WEKNORA_FORMAT env-var fallback
honored before TTY-resolved default. AddFormatFlag retained for the
per-command --jq field-hint Long-text addendum.

~55 production Emit call sites swept across cli/cmd/**: list paths
populate meta.count; mutation paths pass nil meta; envelope.profile
threaded via globalProfile. Existing JSON-shape tests migrated to
decode the envelope wrapper.

Multi-target batch operations get a unified shape via new helpers:
- output.BatchItem + output.WriteBatchEnvelope (§4.5 per-item ok
  pattern; data:[{id, ok, result?|error?}], meta:{count, successes*,
  failures*}; Successes/Failures *int so explicit zero survives
  omitempty in all-fail case).
- cmdutil.RunBatch + cmdutil.EmitBatch + cmdutil.DeletedAtNow +
  cmdutil.ClassifyContextErr collapse the three previously-duplicated
  multi-delete pipelines (doc / chunk / session) into one call site
  pattern. doc upload --recursive uses the same helpers with a per-
  file resultFn. Summary error sets Silent:true so the stderr
  envelope path doesn't duplicate the stdout batch detail (exit 1
  preserved via Code → ExitCode).

ConfirmDestructive / ConfirmDestructiveBatch extended with action +
retryCmd parameters. Every destructive command (kb delete, kb edit,
doc delete, doc delete --all, agent delete, agent edit, session
delete, chunk delete, auth logout, api -X DELETE) now attaches
error.risk.{level:"destructive", action:"<noun.verb>"} +
error.retry_command on the exit-10 envelope. kb edit / agent edit
also gain the destructive guard wiring (CHANGELOG listed them as
gated but they were silently executing without -y).

MCP tool handlers' 31 error paths return CallToolResult with
IsError + Content text fallback + StructuredContent (envelope.error
shape via cmdutil.ErrorToDetail). Handler Out type changed from
typed *sdk.X to any so the go-sdk auto-marshal doesn't overwrite
StructuredContent with a zero-struct on error returns. Success path
manually populates CallToolResult.StructuredContent via successResult
helper.

weknora api cleanup:
- -d/--data flag removed; body via --input <file> or --input -
  (stdin) only. Aligns with gh / curl convention.
- HTTP method whitelist removed; any non-empty method accepted.
- HTTP Retry-After header → cmdutil.Error.RetryAfterSeconds →
  envelope.error.retry_after_seconds.
- runAPIPaginated raw-passthrough fallback now wraps response in
  envelope so --paginate never emits bare JSON to stdout.

Test sweep: ~60 cmd/** tests migrated to decode envelope shape.
9 wire-contract goldens updated under cli/acceptance/testdata/wire/.

Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §4 / §5
This commit is contained in:
nullkey
2026-05-21 18:41:56 +08:00
committed by lyingbug
parent 733bb3aaa1
commit ad150c7126
96 changed files with 2354 additions and 864 deletions
+2 -7
View File
@@ -101,17 +101,12 @@ func MergeAgentConfig(base *sdk.AgentConfig, ov AgentConfigFlags) *sdk.AgentConf
return &out
}
// skeletonCommentVersion is embedded in the skeleton header so users
// regenerating an outdated template after a schema bump can spot the
// version mismatch.
const skeletonCommentVersion = "v0.6 / 34 fields"
// GenerateAgentSkeleton writes a commented YAML template with every
// AgentConfig field at its zero value to w. Used by
// `agent create --generate-skeleton` so users get a ready-to-edit
// starting point without authoring the 34-field schema from memory.
// starting point without authoring the full schema from memory.
func GenerateAgentSkeleton(w io.Writer) error {
const skeleton = `# WeKnora AgentConfig skeleton (` + skeletonCommentVersion + `)
const skeleton = `# WeKnora AgentConfig YAML skeleton
# Edit this file and pass it to:
# weknora agent create "My Agent" --model <id> --config-file <this-file>
# Hot-path flags on the create command override values set here.
+128
View File
@@ -0,0 +1,128 @@
// Package cmdutil — batch.go provides reusable plumbing for multi-target
// mutations that emit the §4.5 batch envelope.
//
// Three pieces:
// - BatchOutcome: per-target structured outcome (preserves argv order).
// - RunBatch: drives a slice of targets through a closure, collecting
// outcomes. Stops on context cancellation; keep-going on per-item err.
// - EmitBatch: renders the outcomes — JSON/NDJSON via output.WriteBatchEnvelope,
// text via per-item "OK <id>" / "FAIL <id>: <msg>".
package cmdutil
import (
"context"
"errors"
"fmt"
"io"
"time"
"github.com/Tencent/WeKnora/cli/internal/output"
)
// BatchOutcome is one per-target result preserving argv order. Err==nil ⇒ success.
type BatchOutcome struct {
ID string
Err error
}
// RunBatch invokes op(ctx, id) for each id and collects outcomes in order.
// Per-item errors do not abort the run; context cancellation does (the
// remainder of the slice is marked with the context error).
//
// Returns (outcomes, summaryErr). summaryErr is a typed *Error with
// CodeOperationFailed when any per-item op failed, nil otherwise. Callers
// emit the outcomes before returning summaryErr so partial-success data
// reaches stdout.
func RunBatch(ctx context.Context, ids []string, op func(context.Context, string) error) ([]BatchOutcome, error) {
outcomes := make([]BatchOutcome, 0, len(ids))
failed := 0
for _, id := range ids {
select {
case <-ctx.Done():
outcomes = append(outcomes, BatchOutcome{ID: id, Err: ctx.Err()})
failed++
continue
default:
}
err := op(ctx, id)
outcomes = append(outcomes, BatchOutcome{ID: id, Err: err})
if err != nil {
failed++
}
}
if failed > 0 {
return outcomes, &Error{
Code: CodeOperationFailed,
Message: fmt.Sprintf("%d/%d operation(s) failed", failed, len(ids)),
// Silent suppresses the stderr error envelope because the caller
// already emitted the batch envelope to stdout (§4.5). The exit code
// still propagates via Error.Code → ExitCode (falls through to 1).
Silent: true,
}
}
return outcomes, nil
}
// EmitBatch writes the per-item outcomes per --format. JSON/NDJSON emit
// the §4.5 batch envelope; human/text mode emits per-line "OK <id>" /
// "FAIL <id>: <msg>".
//
// resultFn builds the per-item Result map for successes; nil ⇒ omit.
// A typical resultFn returns map[string]any{"deleted_at": time.Now()....}.
//
// Callers wanting a stable per-item timestamp pass time.Now() via
// resultFn so tests can pin the clock with SetDeletedAtClock.
func EmitBatch(outcomes []BatchOutcome, fopts *FormatOptions, w io.Writer, resultFn func(id string) any) error {
if fopts.WantsJSON() {
items := make([]output.BatchItem, len(outcomes))
for i, o := range outcomes {
items[i] = output.BatchItem{ID: o.ID, OK: o.Err == nil}
if o.Err != nil {
items[i].Error = ErrorToDetail(o.Err)
} else if resultFn != nil {
items[i].Result = resultFn(o.ID)
}
}
return output.WriteBatchEnvelope(w, items, fopts.TTY, globalProfile)
}
for _, o := range outcomes {
if o.Err == nil {
fmt.Fprintf(w, "OK %s\n", o.ID)
continue
}
fmt.Fprintf(w, "FAIL %s: %s\n", o.ID, o.Err)
}
return nil
}
// deletedAtClock is the clock source for DeletedAtNow. Overridable in tests
// to make per-item timestamps deterministic.
var deletedAtClock = time.Now
// DeletedAtNow is the canonical resultFn for delete batches that report
// {deleted_at: <RFC3339>} per success. Tests can freeze the clock via
// SetDeletedAtClock(func() time.Time { return fixed }).
func DeletedAtNow(id string) any {
return map[string]any{"deleted_at": deletedAtClock().Format(time.RFC3339)}
}
// SetDeletedAtClock overrides the time source used by DeletedAtNow. Returns
// a cleanup func that restores time.Now. For test use only.
func SetDeletedAtClock(clock func() time.Time) func() {
deletedAtClock = clock
return func() { deletedAtClock = time.Now }
}
// ClassifyContextErr maps a context error to the appropriate operation code.
// Falls back to CodeOperationFailed when err is nil or not a context signal.
func ClassifyContextErr(err error) ErrorCode {
switch {
case errors.Is(err, context.Canceled):
return CodeOperationCancelled
case errors.Is(err, context.DeadlineExceeded):
return CodeOperationTimeout
default:
return CodeOperationFailed
}
}
+193
View File
@@ -0,0 +1,193 @@
package cmdutil
import (
"bytes"
"context"
"errors"
"fmt"
"strings"
"testing"
"time"
)
// TestRunBatch_AllSuccess verifies that 3 ids all succeed: outcomes are
// ordered and summaryErr is nil.
func TestRunBatch_AllSuccess(t *testing.T) {
ids := []string{"a", "b", "c"}
op := func(_ context.Context, id string) error { return nil }
outcomes, err := RunBatch(context.Background(), ids, op)
if err != nil {
t.Fatalf("expected nil summaryErr; got %v", err)
}
if len(outcomes) != 3 {
t.Fatalf("expected 3 outcomes; got %d", len(outcomes))
}
for i, o := range outcomes {
if o.ID != ids[i] {
t.Errorf("outcomes[%d].ID = %q, want %q", i, o.ID, ids[i])
}
if o.Err != nil {
t.Errorf("outcomes[%d].Err = %v, want nil", i, o.Err)
}
}
}
// TestRunBatch_PartialFailure verifies that one failing id yields summaryErr
// with CodeOperationFailed while successful outcomes are preserved.
func TestRunBatch_PartialFailure(t *testing.T) {
ids := []string{"ok1", "fail", "ok2"}
errFail := errors.New("something went wrong")
op := func(_ context.Context, id string) error {
if id == "fail" {
return errFail
}
return nil
}
outcomes, summaryErr := RunBatch(context.Background(), ids, op)
if summaryErr == nil {
t.Fatal("expected non-nil summaryErr")
}
typedErr := AsError(summaryErr)
if typedErr == nil {
t.Fatalf("summaryErr is not *Error; got %T %v", summaryErr, summaryErr)
}
if typedErr.Code != CodeOperationFailed {
t.Errorf("summaryErr.Code = %q, want %q", typedErr.Code, CodeOperationFailed)
}
if !strings.Contains(typedErr.Message, "1/3") {
t.Errorf("summaryErr.Message = %q, expected 1/3 ratio", typedErr.Message)
}
if len(outcomes) != 3 {
t.Fatalf("expected 3 outcomes; got %d", len(outcomes))
}
if outcomes[1].Err != errFail {
t.Errorf("outcomes[1].Err = %v, want %v", outcomes[1].Err, errFail)
}
if outcomes[0].Err != nil || outcomes[2].Err != nil {
t.Error("expected outcomes[0] and outcomes[2] to have nil Err")
}
}
// TestRunBatch_ContextCancellation verifies that once the context is cancelled,
// remaining ids are marked with the context error without calling op.
func TestRunBatch_ContextCancellation(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
ids := []string{"first", "second", "third"}
opCalled := 0
op := func(ctx context.Context, id string) error {
opCalled++
if id == "first" {
cancel() // cancel after the first item
}
return nil
}
outcomes, summaryErr := RunBatch(ctx, ids, op)
// summaryErr must be non-nil (cancelled items counted as failed)
if summaryErr == nil {
t.Fatal("expected non-nil summaryErr due to cancellation")
}
if len(outcomes) != 3 {
t.Fatalf("expected 3 outcomes; got %d", len(outcomes))
}
// "second" and "third" should have ctx.Err() as their error
for _, id := range []string{"second", "third"} {
var found *BatchOutcome
for i := range outcomes {
if outcomes[i].ID == id {
found = &outcomes[i]
break
}
}
if found == nil {
t.Fatalf("missing outcome for id %q", id)
}
if !errors.Is(found.Err, context.Canceled) {
t.Errorf("outcome[%s].Err = %v, want context.Canceled", id, found.Err)
}
}
}
// TestEmitBatch_JSON_Envelope verifies that the JSON path emits a valid §4.5
// batch envelope with correct ok/error/result fields.
func TestEmitBatch_JSON_Envelope(t *testing.T) {
outcomes := []BatchOutcome{
{ID: "x", Err: nil},
{ID: "y", Err: NewError(CodeResourceNotFound, "not found")},
}
fopts := &FormatOptions{Mode: FormatJSON, TTY: false}
var buf bytes.Buffer
err := EmitBatch(outcomes, fopts, &buf, func(id string) any {
return map[string]any{"deleted_at": "2026-01-01T00:00:00Z"}
})
if err != nil {
t.Fatalf("EmitBatch error: %v", err)
}
got := buf.String()
if !strings.Contains(got, `"ok":true`) {
t.Errorf("expected ok:true in envelope; got %q", got)
}
if !strings.Contains(got, `"id":"x"`) {
t.Errorf("expected id:x; got %q", got)
}
if !strings.Contains(got, `"id":"y"`) {
t.Errorf("expected id:y; got %q", got)
}
if !strings.Contains(got, `"deleted_at":"2026-01-01T00:00:00Z"`) {
t.Errorf("expected result.deleted_at for x; got %q", got)
}
if !strings.Contains(got, `"type":"resource.not_found"`) {
t.Errorf("expected error.type for y; got %q", got)
}
// meta.failures should be 1
if !strings.Contains(got, `"failures":1`) {
t.Errorf("expected meta.failures:1; got %q", got)
}
}
// TestDeletedAtNow_FixedClock verifies that SetDeletedAtClock overrides the
// timestamp used by DeletedAtNow, making per-item values deterministic in tests.
func TestDeletedAtNow_FixedClock(t *testing.T) {
fixed := time.Date(2026, 5, 20, 0, 0, 0, 0, time.UTC)
defer SetDeletedAtClock(func() time.Time { return fixed })()
got := DeletedAtNow("irrelevant")
m, ok := got.(map[string]any)
if !ok {
t.Fatalf("DeletedAtNow returned %T, want map[string]any", got)
}
want := fixed.Format(time.RFC3339)
if m["deleted_at"] != want {
t.Errorf("deleted_at = %q, want %q", m["deleted_at"], want)
}
}
// TestEmitBatch_Text_PerLine verifies that the human/text path emits
// "OK <id>" / "FAIL <id>: <msg>" per line.
func TestEmitBatch_Text_PerLine(t *testing.T) {
outcomes := []BatchOutcome{
{ID: "x", Err: nil},
{ID: "y", Err: fmt.Errorf("boom")},
}
fopts := &FormatOptions{Mode: FormatHuman}
var buf bytes.Buffer
err := EmitBatch(outcomes, fopts, &buf, nil)
if err != nil {
t.Fatalf("EmitBatch error: %v", err)
}
got := buf.String()
if !strings.Contains(got, "OK x\n") {
t.Errorf("expected 'OK x' line; got %q", got)
}
if !strings.Contains(got, "FAIL y: boom\n") {
t.Errorf("expected 'FAIL y: boom' line; got %q", got)
}
}
+14 -4
View File
@@ -13,7 +13,10 @@ import (
// — one -y confirms all items in the batch.
//
// Pass n = total count of items about to be deleted.
func ConfirmDestructiveBatch(p prompt.Prompter, yes, jsonOut bool, what string, n int) error {
// action is the namespaced action verb (e.g. "doc.delete") for the risk envelope.
// retryCmd is the directly-executable retry argv (e.g. "weknora doc delete a b -y");
// pass "" when no clean retry argv is available.
func ConfirmDestructiveBatch(p prompt.Prompter, yes, jsonOut bool, what string, n int, action, retryCmd string) error {
if yes {
return nil
}
@@ -21,7 +24,9 @@ func ConfirmDestructiveBatch(p prompt.Prompter, yes, jsonOut bool, what string,
return NewError(
CodeInputConfirmationRequired,
fmt.Sprintf("delete %d %s(s) requires explicit confirmation: re-run with -y/--yes", n, what),
)
).
WithRetryCommand(retryCmd).
WithRisk("destructive", action)
}
ok, err := p.Confirm(fmt.Sprintf("Delete %d %s(s)? This cannot be undone.", n, what), false)
if err != nil {
@@ -51,7 +56,10 @@ func ConfirmDestructiveBatch(p prompt.Prompter, yes, jsonOut bool, what string,
// proceed. See cli/README.md "Exit codes".
//
// `yes` should be sourced from the persistent global -y/--yes flag.
func ConfirmDestructive(p prompt.Prompter, yes, jsonOut bool, what, id string) error {
// action is the namespaced action verb (e.g. "kb.delete") for the risk envelope.
// retryCmd is the directly-executable retry argv (e.g. "weknora kb delete kb_x -y");
// pass "" when no clean retry argv is available.
func ConfirmDestructive(p prompt.Prompter, yes, jsonOut bool, what, id, action, retryCmd string) error {
if yes {
return nil
}
@@ -59,7 +67,9 @@ func ConfirmDestructive(p prompt.Prompter, yes, jsonOut bool, what, id string) e
return NewError(
CodeInputConfirmationRequired,
fmt.Sprintf("delete %s %s requires explicit confirmation: re-run with -y/--yes", what, id),
)
).
WithRetryCommand(retryCmd).
WithRisk("destructive", action)
}
ok, err := p.Confirm(fmt.Sprintf("Delete %s %s? This cannot be undone.", what, id), false)
if err != nil {
+77 -56
View File
@@ -4,41 +4,40 @@ import (
"errors"
"fmt"
"io"
"os"
"sort"
"strings"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/format"
"github.com/Tencent/WeKnora/cli/internal/output"
)
// Typed format modes. Defined as constants to keep mode comparisons
// type-safe and prevent string drift across call sites.
// FormatMode is the resolved --format value (typed enum).
type FormatMode string
const (
FormatText = "text"
FormatJSON = "json"
FormatNDJSON = "ndjson"
FormatHuman FormatMode = "human"
FormatJSON FormatMode = "json"
FormatNDJSON FormatMode = "ndjson"
)
// FormatOptions captures the resolved --format + --jq state for a command.
// Mode is one of FormatText / FormatJSON / FormatNDJSON, or "" before
// Mode is one of FormatHuman / FormatJSON / FormatNDJSON, or "" before
// ResolveDefault has been called.
type FormatOptions struct {
Mode string
Mode FormatMode
JQ string
TTY bool // ResolveDefault populates; Emit reads for indent decision
}
// AddFormatFlag registers --format and --jq on cmd. Optional fieldHints are
// appended to cmd.Long as a documentation aid for --jq projection
// (e.g., `weknora kb list --format json --jq '.[] | {id, name}'`).
//
// Uses cmd.Flags() (local) rather than a root persistent flag — only
// commands that actually honor --format register it, so cobra rejects
// --format on others with "unknown flag" rather than silently ignoring it.
// AddFormatFlag attaches the --jq projection field hints (in cmd.Long) for
// commands that honor --format. The flags themselves are registered as
// persistent globals at the root, so this helper no longer re-registers
// them — it only appends documentation. Callers that don't need field
// hints can skip this call entirely.
func AddFormatFlag(cmd *cobra.Command, fieldHints ...string) {
cmd.Flags().String("format", "", "Output format: text | json | ndjson (default: text in TTY, json in pipe)")
cmd.Flags().StringP("jq", "q", "", "Filter JSON output using a jq `expression` (requires --format json|ndjson)")
if len(fieldHints) > 0 {
sorted := append([]string(nil), fieldHints...)
sort.Strings(sorted)
@@ -55,7 +54,7 @@ func AddFormatFlag(cmd *cobra.Command, fieldHints ...string) {
// CheckFormatFlag resolves --format + --jq from cmd. Returns:
// - (*FormatOptions{Mode:""}, nil) flag not set; caller should call ResolveDefault
// - (*FormatOptions{Mode:v,JQ:q}, nil) valid values
// - (nil, *FlagError) invalid --format, or --jq with explicit --format text
// - (nil, *FlagError) invalid --format, or --jq with explicit --format human
//
// --jq with --format unset is accepted: ResolveDefault below will promote
// the mode to FormatJSON so the filter has somewhere to apply.
@@ -64,19 +63,21 @@ func CheckFormatFlag(cmd *cobra.Command) (*FormatOptions, error) {
if f := cmd.Flags().Lookup("format"); f != nil {
v := f.Value.String()
switch v {
case "", FormatText, FormatJSON, FormatNDJSON:
fopts.Mode = v
case "":
// unset; caller calls ResolveDefault
case "human", "json", "ndjson":
fopts.Mode = FormatMode(v)
default:
return nil, NewFlagError(fmt.Errorf("invalid --format %q: must be text | json | ndjson", v))
return nil, NewFlagError(fmt.Errorf("invalid --format %q: must be human | json | ndjson", v))
}
}
if f := cmd.Flags().Lookup("jq"); f != nil {
fopts.JQ = f.Value.String()
}
// --jq only meaningful for JSON-shaped output. Reject the explicit
// `--format text --jq ...` combination; the `--jq` with --format unset
// `--format human --jq ...` combination; the `--jq` with --format unset
// case is handled by ResolveDefault.
if fopts.JQ != "" && fopts.Mode == FormatText {
if fopts.JQ != "" && fopts.Mode == FormatHuman {
return nil, NewFlagError(errors.New("--jq requires --format json|ndjson"))
}
return fopts, nil
@@ -88,48 +89,68 @@ func (o *FormatOptions) WantsJSON() bool {
return o.Mode == FormatJSON || o.Mode == FormatNDJSON
}
// Emit serializes v according to the resolved Mode + JQ. For ndjson, slice
// values are split element-per-line (per ndjson.org); for json, v is
// emitted as-is. When JQ is set, the jq expression runs against the
// marshaled JSON and each result becomes a line. Text mode is the caller's
// job — Emit returns an error so a missed dispatch surfaces loudly.
func (o *FormatOptions) Emit(w io.Writer, v any) error {
// Emit serializes data wrapped in the success envelope (FormatJSON
// path) or as bare NDJSON lines (FormatNDJSON path). meta is optional
// (pass nil for mutation commands without batch counts).
//
// FormatJSON path: envelope is {ok:true, data:..., meta?:..., _notice?:...}.
// Indent is determined by o.TTY (populated by ResolveDefault).
// When o.JQ is set, jq evaluates against the full envelope JSON, so users
// project with ".data[]", ".meta.count", etc.
//
// FormatNDJSON path: emits one bare JSON object per line (no envelope).
// Matches spec §5 NDJSON event-passthrough semantics.
//
// FormatHuman path returns an error so a missed dispatch surfaces loudly.
func (o *FormatOptions) Emit(w io.Writer, data any, meta *output.Meta) error {
switch o.Mode {
case FormatJSON:
return format.WriteJSONFiltered(w, v, nil, o.JQ)
case FormatNDJSON:
// jq output is naturally line-per-result → already valid NDJSON.
// Without jq, split arrays per ndjson.org (one object per line).
if o.JQ != "" {
return format.WriteJSONFiltered(w, v, nil, o.JQ)
env := output.Envelope{
OK: true,
Data: data,
Meta: meta,
Notice: output.GetNotice(),
Profile: globalProfile,
}
return format.WriteJSONFiltered(w, env, nil, o.JQ)
}
return format.WriteNDJSON(w, v)
case FormatText:
return fmt.Errorf("FormatOptions.Emit: cannot emit text mode as JSON; caller must render text separately")
return output.WriteEnvelope(w, data, meta, o.TTY, globalProfile)
case FormatNDJSON:
if o.JQ != "" {
return format.WriteJSONFiltered(w, data, nil, o.JQ)
}
return format.WriteNDJSON(w, data)
case FormatHuman:
return fmt.Errorf("FormatOptions.Emit: cannot emit human mode as JSON; caller must render human-readable separately")
default:
return fmt.Errorf("FormatOptions.Emit: unknown mode %q", o.Mode)
}
}
// ResolveDefault fills in Mode using TTY detection when the user didn't pass
// --format explicitly. Pass iostreams.IO.IsStdoutTTY() as isTTY.
// No-op if Mode is already set.
//
// `--jq` without an explicit `--format` forces JSON regardless of TTY:
// the filter has no meaning in text mode, so silently dropping it would
// surprise the user. The `--jq` + `--format text` combination is caught
// up-front by CheckFormatFlag.
func (o *FormatOptions) ResolveDefault(isTTY bool) {
if o.Mode != "" {
return
}
if o.JQ != "" {
o.Mode = FormatJSON
return
}
if isTTY {
o.Mode = FormatText
} else {
// ResolveDefault fills in Mode when the caller has not explicitly set it:
// - Mode defaults to FormatJSON
// - TTY only affects the indent decision (auto-indent in TTY; compact in pipe)
// - For human-readable rendering, pass --format human explicitly
func (o *FormatOptions) ResolveDefault(tty bool) {
o.TTY = tty
if o.Mode == "" {
o.Mode = FormatJSON
}
}
// FromEnv reads WEKNORA_FORMAT and applies it when Mode hasn't been set
// by --format. Call between CheckFormatFlag and ResolveDefault.
//
// Invalid env values are silently ignored (the user's --format on a
// later invocation will still take precedence).
func (o *FormatOptions) FromEnv() {
if o.Mode != "" {
return
}
v := os.Getenv("WEKNORA_FORMAT")
switch v {
case "human", "json", "ndjson":
o.Mode = FormatMode(v)
}
}
@@ -0,0 +1,88 @@
package cmdutil_test
import (
"bytes"
"strings"
"testing"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/output"
)
func TestEmit_WrapsInEnvelope(t *testing.T) {
var buf bytes.Buffer
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}
data := []map[string]string{{"id": "kb_x"}, {"id": "kb_y"}}
if err := fopts.Emit(&buf, data, nil); err != nil {
t.Fatalf("unexpected error: %v", err)
}
got := buf.String()
if !strings.Contains(got, `"ok":true`) {
t.Errorf("expected envelope ok:true; got %q", got)
}
if !strings.Contains(got, `"data":[`) {
t.Errorf("expected data array; got %q", got)
}
}
func TestEmit_WithMeta(t *testing.T) {
var buf bytes.Buffer
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}
meta := &output.Meta{Count: 2, HasMore: true}
if err := fopts.Emit(&buf, []string{"a", "b"}, meta); err != nil {
t.Fatalf("unexpected error: %v", err)
}
got := buf.String()
if !strings.Contains(got, `"count":2`) {
t.Errorf("expected meta.count; got %q", got)
}
if !strings.Contains(got, `"has_more":true`) {
t.Errorf("expected meta.has_more; got %q", got)
}
}
func TestEmit_NDJSON_NoEnvelope(t *testing.T) {
// NDJSON path is event-passthrough; no envelope wrapping per spec §5.
var buf bytes.Buffer
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatNDJSON}
data := []map[string]string{{"id": "a"}, {"id": "b"}}
if err := fopts.Emit(&buf, data, nil); err != nil {
t.Fatalf("unexpected error: %v", err)
}
got := buf.String()
if strings.Contains(got, `"ok":true`) {
t.Errorf("NDJSON path should not wrap in envelope; got %q", got)
}
// Expect 2 lines, one per item
lines := strings.Split(strings.TrimRight(got, "\n"), "\n")
if len(lines) != 2 {
t.Errorf("expected 2 NDJSON lines; got %d: %q", len(lines), got)
}
}
func TestEmit_TTYIndents(t *testing.T) {
var buf bytes.Buffer
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON, TTY: true}
if err := fopts.Emit(&buf, map[string]string{"id": "x"}, nil); err != nil {
t.Fatalf("unexpected error: %v", err)
}
got := buf.String()
if !strings.Contains(got, "\n \"") {
t.Errorf("expected indented multi-line output (TTY=true); got %q", got)
}
}
func TestEmit_PopulatesProfile(t *testing.T) {
cmdutil.SetProfile("staging")
t.Cleanup(func() { cmdutil.SetProfile("") })
var buf bytes.Buffer
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}
if err := fopts.Emit(&buf, map[string]string{"id": "x"}, nil); err != nil {
t.Fatalf("unexpected error: %v", err)
}
got := buf.String()
if !strings.Contains(got, `"profile":"staging"`) {
t.Errorf("expected profile:staging in envelope; got %q", got)
}
}
+125 -31
View File
@@ -4,6 +4,7 @@ import (
"bytes"
"encoding/json"
"errors"
"strings"
"testing"
"github.com/spf13/cobra"
@@ -13,20 +14,26 @@ func TestCheckFormatFlags(t *testing.T) {
cases := []struct {
name string
args []string
wantMode string // "text" | "json" | "ndjson" | "" (unset)
wantMode FormatMode // FormatHuman | FormatJSON | FormatNDJSON | "" (unset)
wantErr bool
}{
// Unset → Mode is "" (caller resolves TTY default via ResolveDefault).
// Unset → Mode is "" (caller resolves default via ResolveDefault).
{"default", []string{}, "", false},
{"explicit text", []string{"--format", "text"}, "text", false},
{"json", []string{"--format", "json"}, "json", false},
{"ndjson", []string{"--format", "ndjson"}, "ndjson", false},
{"explicit human", []string{"--format", "human"}, FormatHuman, false},
{"json", []string{"--format", "json"}, FormatJSON, false},
{"ndjson", []string{"--format", "ndjson"}, FormatNDJSON, false},
{"invalid value", []string{"--format", "yaml"}, "", true},
// v0.7 BREAKING: "text" is no longer a valid --format value.
{"text rejected", []string{"--format", "text"}, "", true},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
cmd := &cobra.Command{}
AddFormatFlag(cmd)
// --format / --jq are persistent root flags in production; register
// them on this bare cmd so the test can exercise CheckFormatFlag in
// isolation.
cmd.PersistentFlags().String("format", "", "")
cmd.PersistentFlags().String("jq", "", "")
cmd.SetArgs(tc.args)
cmd.RunE = func(c *cobra.Command, _ []string) error {
opts, err := CheckFormatFlag(c)
@@ -45,9 +52,9 @@ func TestCheckFormatFlags(t *testing.T) {
func TestFormatOptions_NDJSONSplitsList(t *testing.T) {
var buf bytes.Buffer
fopts := &FormatOptions{Mode: "ndjson"}
fopts := &FormatOptions{Mode: FormatNDJSON}
arr := []map[string]string{{"id": "a"}, {"id": "b"}}
if err := fopts.Emit(&buf, arr); err != nil {
if err := fopts.Emit(&buf, arr, nil); err != nil {
t.Fatalf("Emit: %v", err)
}
want := `{"id":"a"}` + "\n" + `{"id":"b"}` + "\n"
@@ -58,45 +65,68 @@ func TestFormatOptions_NDJSONSplitsList(t *testing.T) {
func TestFormatOptions_JSONEmitsArray(t *testing.T) {
var buf bytes.Buffer
fopts := &FormatOptions{Mode: "json"}
fopts := &FormatOptions{Mode: FormatJSON}
arr := []map[string]string{{"id": "a"}, {"id": "b"}}
if err := fopts.Emit(&buf, arr); err != nil {
if err := fopts.Emit(&buf, arr, nil); err != nil {
t.Fatalf("Emit: %v", err)
}
// Expect a single JSON array, e.g. [{"id":"a"},{"id":"b"}]
var got []map[string]string
if err := json.Unmarshal(buf.Bytes(), &got); err != nil {
t.Fatalf("not valid JSON: %v\n%s", err, buf.String())
// v0.7: JSON path wraps in success envelope {ok:true, data:[...]}.
// Unmarshal the envelope and check data array length.
var env struct {
OK bool `json:"ok"`
Data []map[string]string `json:"data"`
}
if len(got) != 2 {
t.Errorf("got %d items, want 2", len(got))
if err := json.Unmarshal(buf.Bytes(), &env); err != nil {
t.Fatalf("not valid envelope JSON: %v\n%s", err, buf.String())
}
if !env.OK {
t.Errorf("expected ok:true in envelope")
}
if len(env.Data) != 2 {
t.Errorf("got %d items, want 2", len(env.Data))
}
}
func TestFormatOptions_TextModeReturnsError(t *testing.T) {
fopts := &FormatOptions{Mode: "text"}
err := fopts.Emit(&bytes.Buffer{}, map[string]string{"a": "b"})
func TestFormatOptions_HumanModeReturnsError(t *testing.T) {
fopts := &FormatOptions{Mode: FormatHuman}
err := fopts.Emit(&bytes.Buffer{}, map[string]string{"a": "b"}, nil)
if err == nil {
t.Error("expected error for text mode, got nil")
t.Error("expected error for human mode, got nil")
}
}
// TestResolveDefault_AlwaysJSON verifies v0.7 semantics: default is FormatJSON
// regardless of whether stdout is a TTY (BREAKING change from v0.6).
func TestResolveDefault_AlwaysJSON(t *testing.T) {
for _, isTTY := range []bool{true, false} {
o := &FormatOptions{}
o.ResolveDefault(isTTY)
if o.Mode != FormatJSON {
t.Errorf("isTTY=%v: expected default FormatJSON, got %v", isTTY, o.Mode)
}
if o.TTY != isTTY {
t.Errorf("isTTY=%v: TTY field not propagated", isTTY)
}
}
}
func TestResolveDefault(t *testing.T) {
cases := []struct {
name string
mode string // pre-set Mode
mode FormatMode // pre-set Mode
jq string
isTTY bool
wantMode string
wantMode FormatMode
}{
{"empty isTTY", "", "", true, "text"},
{"empty no-tty", "", "", false, "json"},
{"already set keeps value tty", "ndjson", "", true, "ndjson"},
{"already set keeps value no-tty", "json", "", false, "json"},
// v0.7: empty Mode always resolves to FormatJSON regardless of TTY.
{"empty isTTY", "", "", true, FormatJSON},
{"empty no-tty", "", "", false, FormatJSON},
{"already set keeps value tty", FormatNDJSON, "", true, FormatNDJSON},
{"already set keeps value no-tty", FormatJSON, "", false, FormatJSON},
// --jq with unset --format promotes to JSON regardless of TTY so the
// filter has somewhere to apply (silent text drop would surprise users).
{"jq forces json on TTY", "", ".[]", true, "json"},
{"jq with explicit ndjson preserved", "ndjson", ".[]", true, "ndjson"},
// filter has somewhere to apply (silent human drop would surprise users).
{"jq forces json on TTY", "", ".[]", true, FormatJSON},
{"jq with explicit ndjson preserved", FormatNDJSON, ".[]", true, FormatNDJSON},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
@@ -117,12 +147,18 @@ func TestCheckFormatFlag_InvalidExitTwo(t *testing.T) {
args []string
}{
{"invalid format value", []string{"--format", "yaml"}},
{"jq with explicit text mode", []string{"--format", "text", "--jq", ".id"}},
// v0.7: "text" is rejected; "human" is the valid human-readable value.
{"text rejected as invalid", []string{"--format", "text"}},
{"jq with explicit human mode", []string{"--format", "human", "--jq", ".id"}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
cmd := &cobra.Command{}
AddFormatFlag(cmd)
// --format / --jq are persistent root flags in production; register
// them on this bare cmd so the test can exercise CheckFormatFlag in
// isolation.
cmd.PersistentFlags().String("format", "", "")
cmd.PersistentFlags().String("jq", "", "")
cmd.SetArgs(tc.args)
var got error
cmd.RunE = func(c *cobra.Command, _ []string) error {
@@ -144,3 +180,61 @@ func TestCheckFormatFlag_InvalidExitTwo(t *testing.T) {
})
}
}
func TestCheckFormatFlag_InvalidValueRejected(t *testing.T) {
for _, v := range []string{"text", "yaml", "xml", "table"} {
v := v
t.Run(v, func(t *testing.T) {
cmd := &cobra.Command{}
cmd.Flags().String("format", "", "")
_ = cmd.Flags().Set("format", v)
_, err := CheckFormatFlag(cmd)
if err == nil {
t.Fatalf("expected error for --format %q", v)
}
if !strings.Contains(err.Error(), "human | json | ndjson") {
t.Errorf("expected enum hint for --format %q; got %v", v, err)
}
})
}
}
func TestCheckFormatFlag_HumanAccepted(t *testing.T) {
cmd := &cobra.Command{}
cmd.Flags().String("format", "", "")
_ = cmd.Flags().Set("format", "human")
o, err := CheckFormatFlag(cmd)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if o.Mode != FormatHuman {
t.Errorf("got %v, want FormatHuman", o.Mode)
}
}
func TestFromEnv_AppliesWEKNORA_FORMAT(t *testing.T) {
t.Setenv("WEKNORA_FORMAT", "ndjson")
o := &FormatOptions{}
o.FromEnv()
if o.Mode != FormatNDJSON {
t.Errorf("expected FormatNDJSON from env; got %v", o.Mode)
}
}
func TestFromEnv_PrecedenceFlagOverridesEnv(t *testing.T) {
t.Setenv("WEKNORA_FORMAT", "ndjson")
o := &FormatOptions{Mode: FormatJSON}
o.FromEnv()
if o.Mode != FormatJSON {
t.Errorf("flag should win over env; got %v", o.Mode)
}
}
func TestFromEnv_InvalidValueIgnored(t *testing.T) {
t.Setenv("WEKNORA_FORMAT", "yaml")
o := &FormatOptions{}
o.FromEnv()
if o.Mode != "" {
t.Errorf("invalid env should be ignored; got %v", o.Mode)
}
}
+1 -1
View File
@@ -39,7 +39,7 @@ func AddLogLevelFlag(cmd *cobra.Command) {
//
// Invalid env values fall through to the next priority (no error — env is
// best-effort). The stderr writer is retained in the signature for symmetry
// with ApplyLogLevel callers but is unused in v0.6.
// with ApplyLogLevel callers but is unused at the OS level.
func ResolveLogLevel(cmd *cobra.Command, _ io.Writer) (string, bool) {
// Priority 1: explicit --log-level flag.
if cmd != nil {
+107 -52
View File
@@ -3,6 +3,7 @@ package mcp
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"strings"
@@ -10,10 +11,57 @@ import (
mcpsdk "github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/sse"
sdk "github.com/Tencent/WeKnora/client"
)
// toolErrorResult builds an error CallToolResult with IsError=true, a
// human-readable text fallback (Content), and the error envelope payload
// (StructuredContent). Reuses cmdutil.ErrorToDetail so the hint / retry /
// risk / detail fallback table stays single-source.
//
// Returns nil when err is nil; callers should only invoke on a real error.
//
// CAVEAT (go-sdk v1.6.0): SetError(err) clobbers Content; we manually
// build CallToolResult instead.
func toolErrorResult(err error) *mcpsdk.CallToolResult {
if err == nil {
return nil
}
detail := cmdutil.ErrorToDetail(err)
textLine := detail.Type + ": " + detail.Message
if detail.Hint != "" {
textLine += "\nhint: " + detail.Hint
}
if detail.RetryCommand != "" {
textLine += "\nretry: " + detail.RetryCommand
}
// StructuredContent accepts any; pass *ErrDetail directly (no round-trip).
return &mcpsdk.CallToolResult{
IsError: true,
Content: []mcpsdk.Content{&mcpsdk.TextContent{Text: textLine}},
StructuredContent: detail,
}
}
// successResult builds a CallToolResult with StructuredContent = payload.
// Using Out=any in all handlers disables the SDK auto-marshal path (which
// would overwrite our StructuredContent with a zero-struct when the handler
// returns a typed nil). We manually populate both StructuredContent and a
// text Content fallback so the shape is identical on success and error.
func successResult(payload any) *mcpsdk.CallToolResult {
return &mcpsdk.CallToolResult{
StructuredContent: payload,
Content: []mcpsdk.Content{&mcpsdk.TextContent{Text: marshalToString(payload)}},
}
}
func marshalToString(v any) string {
b, _ := json.Marshal(v)
return string(b)
}
// Narrow per-domain service interfaces. ServiceClient (server.go) embeds
// them all; *sdk.Client satisfies the union implicitly.
@@ -61,6 +109,13 @@ type agentInvokeService interface {
// is a deliberate API expansion - the agent-callable surface is the
// reason this CLI ships an MCP server, not its CLI command list, so this
// list must be maintained by hand.
//
// TODO(v0.8): add OutputSchema to each mcpsdk.Tool registration so agents
// can type-check responses without structural probing. Currently omitted
// because the Out type is `any` on all handlers (required to suppress the
// SDK's auto-marshal which clobbers our manually-populated StructuredContent).
// When go-sdk exposes a typed OutputSchema field independent of the handler
// Out type, populate it from the corresponding *Output struct.
func registerTools(server *mcpsdk.Server, svc ServiceClient) {
addKBList(server, svc)
addKBView(server, svc)
@@ -86,15 +141,15 @@ func addKBList(server *mcpsdk.Server, svc knowledgeBaseService) {
mcpsdk.AddTool(server, &mcpsdk.Tool{
Name: "kb_list",
Description: "List all knowledge bases visible to the active WeKnora tenant. No arguments. Returns items[]: each item carries id, name, description, knowledge_count, is_pinned, updated_at - useful for selecting a kb_id to pass to other tools.",
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, _ kbListInput) (*mcpsdk.CallToolResult, kbListOutput, error) {
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, _ kbListInput) (*mcpsdk.CallToolResult, any, error) {
items, err := svc.ListKnowledgeBases(ctx)
if err != nil {
return nil, kbListOutput{}, fmt.Errorf("list knowledge bases: %w", err)
return toolErrorResult(cmdutil.WrapHTTP(err, "list knowledge bases")), nil, nil
}
if items == nil {
items = []sdk.KnowledgeBase{}
}
return nil, kbListOutput{Items: items}, nil
return successResult(kbListOutput{Items: items}), nil, nil
})
}
@@ -108,15 +163,15 @@ func addKBView(server *mcpsdk.Server, svc knowledgeBaseService) {
mcpsdk.AddTool(server, &mcpsdk.Tool{
Name: "kb_view",
Description: "Fetch a knowledge base by ID. Returns the full record including chunking config, embedding/summary model IDs, knowledge_count, and chunk_count.",
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, in kbViewInput) (*mcpsdk.CallToolResult, *sdk.KnowledgeBase, error) {
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, in kbViewInput) (*mcpsdk.CallToolResult, any, error) {
if in.KBID == "" {
return nil, nil, fmt.Errorf("kb_id is required")
return toolErrorResult(cmdutil.NewError(cmdutil.CodeKBIDRequired, "kb_id is required")), nil, nil
}
kb, err := svc.GetKnowledgeBase(ctx, in.KBID)
if err != nil {
return nil, nil, fmt.Errorf("get knowledge base: %w", err)
return toolErrorResult(cmdutil.WrapHTTP(err, "get knowledge base")), nil, nil
}
return nil, kb, nil
return successResult(kb), nil, nil
})
}
@@ -146,9 +201,9 @@ func addDocList(server *mcpsdk.Server, svc knowledgeService) {
mcpsdk.AddTool(server, &mcpsdk.Tool{
Name: "doc_list",
Description: "List documents in a knowledge base, with pagination and optional filters (parse-status, keyword, file_type, source, tag_id, start_time/end_time on updated_at). Returns items[] with id, file_name, title, parse_status, size, updated_at - plus the page/total metadata.",
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, in docListInput) (*mcpsdk.CallToolResult, docListOutput, error) {
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, in docListInput) (*mcpsdk.CallToolResult, any, error) {
if in.KBID == "" {
return nil, docListOutput{}, fmt.Errorf("kb_id is required")
return toolErrorResult(cmdutil.NewError(cmdutil.CodeKBIDRequired, "kb_id is required")), nil, nil
}
page := in.Page
if page < 1 {
@@ -159,7 +214,7 @@ func addDocList(server *mcpsdk.Server, svc knowledgeService) {
size = 20
}
if size > 1000 {
return nil, docListOutput{}, fmt.Errorf("page_size must be in 1..1000")
return toolErrorResult(cmdutil.NewError(cmdutil.CodeInputInvalidArgument, "page_size must be in 1..1000")), nil, nil
}
filter := sdk.KnowledgeListFilter{
ParseStatus: in.Status,
@@ -171,25 +226,25 @@ func addDocList(server *mcpsdk.Server, svc knowledgeService) {
if in.StartTime != "" {
t, err := time.Parse(time.RFC3339, in.StartTime)
if err != nil {
return nil, docListOutput{}, fmt.Errorf("start_time must be RFC3339 (e.g. 2006-01-02T15:04:05Z), got %q", in.StartTime)
return toolErrorResult(cmdutil.NewError(cmdutil.CodeInputInvalidArgument, fmt.Sprintf("start_time must be RFC3339 (e.g. 2006-01-02T15:04:05Z), got %q", in.StartTime))), nil, nil
}
filter.StartTime = t
}
if in.EndTime != "" {
t, err := time.Parse(time.RFC3339, in.EndTime)
if err != nil {
return nil, docListOutput{}, fmt.Errorf("end_time must be RFC3339 (e.g. 2006-01-02T15:04:05Z), got %q", in.EndTime)
return toolErrorResult(cmdutil.NewError(cmdutil.CodeInputInvalidArgument, fmt.Sprintf("end_time must be RFC3339 (e.g. 2006-01-02T15:04:05Z), got %q", in.EndTime))), nil, nil
}
filter.EndTime = t
}
items, total, err := svc.ListKnowledgeWithFilter(ctx, in.KBID, page, size, filter)
if err != nil {
return nil, docListOutput{}, fmt.Errorf("list documents: %w", err)
return toolErrorResult(cmdutil.WrapHTTP(err, "list documents")), nil, nil
}
if items == nil {
items = []sdk.Knowledge{}
}
return nil, docListOutput{Items: items, Page: page, PageSize: size, Total: total}, nil
return successResult(docListOutput{Items: items, Page: page, PageSize: size, Total: total}), nil, nil
})
}
@@ -203,15 +258,15 @@ func addDocView(server *mcpsdk.Server, svc knowledgeService) {
mcpsdk.AddTool(server, &mcpsdk.Tool{
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) {
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, in docViewInput) (*mcpsdk.CallToolResult, any, error) {
if in.DocID == "" {
return nil, nil, fmt.Errorf("doc_id is required")
return toolErrorResult(cmdutil.NewError(cmdutil.CodeInputMissingFlag, "doc_id is required")), nil, nil
}
k, err := svc.GetKnowledge(ctx, in.DocID)
if err != nil {
return nil, nil, fmt.Errorf("get knowledge: %w", err)
return toolErrorResult(cmdutil.WrapHTTP(err, "get knowledge")), nil, nil
}
return nil, k, nil
return successResult(k), nil, nil
})
}
@@ -242,30 +297,30 @@ func addDocDownload(server *mcpsdk.Server, svc knowledgeService) {
mcpsdk.AddTool(server, &mcpsdk.Tool{
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) {
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, in docDownloadInput) (*mcpsdk.CallToolResult, any, error) {
if in.DocID == "" {
return nil, docDownloadOutput{}, fmt.Errorf("doc_id is required")
return toolErrorResult(cmdutil.NewError(cmdutil.CodeInputMissingFlag, "doc_id is required")), nil, nil
}
name, body, err := svc.OpenKnowledgeFile(ctx, in.DocID)
if err != nil {
return nil, docDownloadOutput{}, fmt.Errorf("open knowledge file: %w", err)
return toolErrorResult(cmdutil.WrapHTTP(err, "open knowledge file")), nil, nil
}
defer body.Close()
buf, err := io.ReadAll(io.LimitReader(body, maxDocDownloadBytes+1))
if err != nil {
return nil, docDownloadOutput{}, fmt.Errorf("read knowledge file: %w", err)
return toolErrorResult(cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "read knowledge file")), nil, nil
}
if len(buf) > maxDocDownloadBytes {
return nil, docDownloadOutput{}, fmt.Errorf("document exceeds the %d-byte per-call cap; use search_chunks for excerpts", maxDocDownloadBytes)
return toolErrorResult(cmdutil.NewError(cmdutil.CodeInputInvalidArgument, fmt.Sprintf("document exceeds the %d-byte per-call cap; use search_chunks for excerpts", maxDocDownloadBytes))), nil, nil
}
content, isBase64 := encodeDownload(buf)
return nil, docDownloadOutput{
return successResult(docDownloadOutput{
DocID: in.DocID,
FileName: name,
Bytes: len(buf),
Content: content,
IsBase64: isBase64,
}, nil
}), nil, nil
})
}
@@ -296,17 +351,17 @@ func addSearchChunks(server *mcpsdk.Server, svc knowledgeService) {
Description: "Hybrid (vector + keyword) retrieval against a knowledge base. Returns the top chunks ranked by RRF; use this before chat to ground an answer in cited context. Results include knowledge_id, content, score - feed back into chat as context or display directly.",
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, in searchChunksInput) (*mcpsdk.CallToolResult, any, error) {
if in.KBID == "" {
return nil, nil, fmt.Errorf("kb_id is required")
return toolErrorResult(cmdutil.NewError(cmdutil.CodeKBIDRequired, "kb_id is required")), nil, nil
}
if strings.TrimSpace(in.Query) == "" {
return nil, nil, fmt.Errorf("query cannot be empty")
return toolErrorResult(cmdutil.NewError(cmdutil.CodeInputMissingFlag, "query cannot be empty")), nil, nil
}
limit := in.Limit
if limit < 1 {
limit = 10
}
if limit > 1000 {
return nil, nil, fmt.Errorf("limit must be in 1..1000")
return toolErrorResult(cmdutil.NewError(cmdutil.CodeInputInvalidArgument, "limit must be in 1..1000")), nil, nil
}
results, err := svc.HybridSearch(ctx, in.KBID, &sdk.SearchParams{
QueryText: in.Query,
@@ -315,7 +370,7 @@ func addSearchChunks(server *mcpsdk.Server, svc knowledgeService) {
KeywordThreshold: in.KeywordThreshold,
})
if err != nil {
return nil, nil, fmt.Errorf("hybrid search: %w", err)
return toolErrorResult(cmdutil.WrapHTTP(err, "hybrid search")), nil, nil
}
if len(results) > limit {
results = results[:limit]
@@ -323,7 +378,7 @@ func addSearchChunks(server *mcpsdk.Server, svc knowledgeService) {
if results == nil {
results = []*sdk.SearchResult{}
}
return nil, searchChunksOutput{Results: results}, nil
return successResult(searchChunksOutput{Results: results}), nil, nil
})
}
@@ -351,16 +406,16 @@ func addChat(server *mcpsdk.Server, svc chatService) {
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")
return toolErrorResult(cmdutil.NewError(cmdutil.CodeKBIDRequired, "kb_id is required")), nil, nil
}
if strings.TrimSpace(in.Query) == "" {
return nil, nil, fmt.Errorf("query cannot be empty")
return toolErrorResult(cmdutil.NewError(cmdutil.CodeInputMissingFlag, "query cannot be empty")), nil, nil
}
sessionID := in.SessionID
if sessionID == "" {
sess, err := svc.CreateSession(ctx, &sdk.CreateSessionRequest{Title: "weknora mcp chat"})
if err != nil {
return nil, nil, fmt.Errorf("create chat session: %w", err)
return toolErrorResult(cmdutil.WrapHTTP(err, "create chat session")), nil, nil
}
sessionID = sess.ID
}
@@ -376,16 +431,16 @@ func addChat(server *mcpsdk.Server, svc chatService) {
return nil
})
if streamErr != nil {
return nil, nil, fmt.Errorf("knowledge qa stream: %w", streamErr)
return toolErrorResult(cmdutil.WrapHTTP(streamErr, "knowledge qa stream")), nil, nil
}
if !acc.Done() {
return nil, nil, fmt.Errorf("stream ended without a terminal event")
return toolErrorResult(cmdutil.NewError(cmdutil.CodeSSEStreamAborted, "stream ended without a terminal event")), nil, nil
}
sid := acc.SessionID
if sid == "" {
sid = sessionID
}
return nil, chatOutput{
return successResult(chatOutput{
Answer: acc.Result(),
References: acc.References,
Thinking: acc.Thinking(),
@@ -393,7 +448,7 @@ func addChat(server *mcpsdk.Server, svc chatService) {
AssistantMessageID: acc.AssistantMessageID,
KBID: in.KBID,
Query: in.Query,
}, nil
}), nil, nil
})
}
@@ -409,15 +464,15 @@ func addAgentList(server *mcpsdk.Server, svc agentService) {
mcpsdk.AddTool(server, &mcpsdk.Tool{
Name: "agent_list",
Description: "List the tenant's custom agents. Returns items[] with id, name, description, is_builtin - use to discover an agent_id before agent_invoke.",
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, _ agentListInput) (*mcpsdk.CallToolResult, agentListOutput, error) {
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, _ agentListInput) (*mcpsdk.CallToolResult, any, error) {
items, err := svc.ListAgents(ctx)
if err != nil {
return nil, agentListOutput{}, fmt.Errorf("list agents: %w", err)
return toolErrorResult(cmdutil.WrapHTTP(err, "list agents")), nil, nil
}
if items == nil {
items = []sdk.Agent{}
}
return nil, agentListOutput{Items: items}, nil
return successResult(agentListOutput{Items: items}), nil, nil
})
}
@@ -445,10 +500,10 @@ func addAgentInvoke(server *mcpsdk.Server, svc agentInvokeService) {
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")
return toolErrorResult(cmdutil.NewError(cmdutil.CodeInputMissingFlag, "agent_id is required")), nil, nil
}
if strings.TrimSpace(in.Query) == "" {
return nil, nil, fmt.Errorf("query cannot be empty")
return toolErrorResult(cmdutil.NewError(cmdutil.CodeInputMissingFlag, "query cannot be empty")), nil, nil
}
acc := &sse.AgentAccumulator{}
req := &sdk.AgentQARequest{
@@ -463,7 +518,7 @@ func addAgentInvoke(server *mcpsdk.Server, svc agentInvokeService) {
if sessionID == "" {
sess, err := svc.CreateSession(ctx, &sdk.CreateSessionRequest{Title: "weknora mcp agent_invoke"})
if err != nil {
return nil, nil, fmt.Errorf("create chat session: %w", err)
return toolErrorResult(cmdutil.WrapHTTP(err, "create chat session")), nil, nil
}
sessionID = sess.ID
}
@@ -472,12 +527,12 @@ func addAgentInvoke(server *mcpsdk.Server, svc agentInvokeService) {
return nil
})
if streamErr != nil {
return nil, nil, fmt.Errorf("agent-chat stream: %w", streamErr)
return toolErrorResult(cmdutil.WrapHTTP(streamErr, "agent-chat stream")), nil, nil
}
if !acc.Done() {
return nil, nil, fmt.Errorf("stream ended without a terminal event")
return toolErrorResult(cmdutil.NewError(cmdutil.CodeSSEStreamAborted, "stream ended without a terminal event")), nil, nil
}
return nil, agentInvokeOutput{
return successResult(agentInvokeOutput{
Answer: acc.Answer(),
References: acc.References,
ToolEvents: acc.ToolEvents,
@@ -485,7 +540,7 @@ func addAgentInvoke(server *mcpsdk.Server, svc agentInvokeService) {
SessionID: sessionID,
AgentID: in.AgentID,
Query: in.Query,
}, nil
}), nil, nil
})
}
@@ -515,9 +570,9 @@ func addChunkList(server *mcpsdk.Server, svc chunkListService) {
mcpsdk.AddTool(server, &mcpsdk.Tool{
Name: "chunk_list",
Description: "List chunks of a knowledge document for RAG retrieval debug. Returns at most `limit` chunks starting from ChunkIndex 0; if total chunks exceed limit, truncated_at_limit=true signals the agent to fall back to the CLI for paginated retrieval.",
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, in chunkListInput) (*mcpsdk.CallToolResult, chunkListOutput, error) {
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, in chunkListInput) (*mcpsdk.CallToolResult, any, error) {
if in.DocID == "" {
return nil, chunkListOutput{}, fmt.Errorf("doc_id is required")
return toolErrorResult(cmdutil.NewError(cmdutil.CodeInputMissingFlag, "doc_id is required")), nil, nil
}
// `limit` is typed as int by chunkListInput, so the SDK rejects
// non-numeric values at schema validation (e.g. "limit":"50")
@@ -532,16 +587,16 @@ func addChunkList(server *mcpsdk.Server, svc chunkListService) {
}
chunks, total, err := svc.ListKnowledgeChunks(ctx, in.DocID, 1, limit)
if err != nil {
return nil, chunkListOutput{}, fmt.Errorf("list knowledge chunks: %w", err)
return toolErrorResult(cmdutil.WrapHTTP(err, "list knowledge chunks")), nil, nil
}
if chunks == nil {
chunks = []sdk.Chunk{}
}
return nil, chunkListOutput{
return successResult(chunkListOutput{
Chunks: chunks,
Total: total,
TruncatedAtLimit: total > int64(limit),
}, nil
}), nil, nil
})
}
+104
View File
@@ -0,0 +1,104 @@
package mcp
import (
"strings"
"testing"
mcpsdk "github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/output"
sdk "github.com/Tencent/WeKnora/client"
)
// TestToolErrorResult_TypedError_PopulatesStructuredContent verifies the
// helper maps a typed cmdutil.Error to MCP StructuredContent as *output.ErrDetail.
func TestToolErrorResult_TypedError_PopulatesStructuredContent(t *testing.T) {
err := cmdutil.NewError(cmdutil.CodeAuthUnauthenticated, "no creds")
res := toolErrorResult(err)
if !res.IsError {
t.Errorf("expected IsError true")
}
if res.StructuredContent == nil {
t.Fatal("expected StructuredContent populated")
}
sc, ok := res.StructuredContent.(*output.ErrDetail)
if !ok {
t.Fatalf("StructuredContent has unexpected type %T", res.StructuredContent)
}
if sc.Type != "auth.unauthenticated" {
t.Errorf("type: got %v want auth.unauthenticated", sc.Type)
}
// retry_command should fall back to "weknora auth login" via cmdutil default
if sc.RetryCommand != "weknora auth login" {
t.Errorf("retry_command: got %v", sc.RetryCommand)
}
}
// TestToolErrorResult_TextFallback verifies the human-readable Content[0]
// contains code + message + (hint? + retry?) lines.
func TestToolErrorResult_TextFallback(t *testing.T) {
err := cmdutil.NewError(cmdutil.CodeKBIDRequired, "kb_id is required")
res := toolErrorResult(err)
if len(res.Content) == 0 {
t.Fatal("expected Content[0]")
}
// Assertion is best-effort on the text shape; exact prose may vary
// with hint/retry defaults. Lock the type code prefix.
text := contentText(t, res.Content[0])
if !strings.Contains(text, "local.kb_id_required: kb_id is required") {
t.Errorf("text fallback missing code:message; got %q", text)
}
}
// contentText extracts the Text field from an mcpsdk.Content value.
// Lives in the test file to avoid leaking helpers into production.
func contentText(t *testing.T, c any) string {
t.Helper()
// Direct assertion to the concrete type used by toolErrorResult.
if tc, ok := c.(*mcpsdk.TextContent); ok {
return tc.Text
}
// Fallback: some go-sdk versions may expose a GetText() method.
if tc, ok := c.(interface{ GetText() string }); ok {
return tc.GetText()
}
t.Fatalf("cannot extract text from Content of type %T", c)
return ""
}
// TestToolErrorResult_IsErrorFlagSet verifies IsError is always true.
func TestToolErrorResult_IsErrorFlagSet(t *testing.T) {
res := toolErrorResult(cmdutil.NewError(cmdutil.CodeInputMissingFlag, "doc_id is required"))
if !res.IsError {
t.Error("expected IsError=true")
}
}
// TestToolErrorResult_ContentPresent verifies Content slice is non-empty.
func TestToolErrorResult_ContentPresent(t *testing.T) {
res := toolErrorResult(cmdutil.NewError(cmdutil.CodeInputInvalidArgument, "page_size must be in 1..1000"))
if len(res.Content) == 0 {
t.Error("expected at least one Content item")
}
}
// TestToolErrorResult_NetworkError verifies a network error code round-trips
// through toolErrorResult with the correct type in StructuredContent.
func TestToolErrorResult_NetworkError(t *testing.T) {
err := cmdutil.NewError(cmdutil.CodeNetworkError, "dial failed")
res := toolErrorResult(err)
if !res.IsError {
t.Error("expected IsError=true")
}
sc, ok := res.StructuredContent.(*output.ErrDetail)
if !ok {
t.Fatalf("StructuredContent has unexpected type %T", res.StructuredContent)
}
if sc.Type != "network.error" {
t.Errorf("type: got %v want network.error", sc.Type)
}
}
// Suppress unused-import warning if sdk isn't used in this file.
var _ = sdk.KnowledgeBase{}
+44
View File
@@ -0,0 +1,44 @@
package output
import "io"
// BatchItem is one per-id outcome in a batch operation envelope (§4.5).
type BatchItem struct {
ID string `json:"id"`
OK bool `json:"ok"`
Result any `json:"result,omitempty"`
Error *ErrDetail `json:"error,omitempty"`
}
// WriteBatchEnvelope writes a batch operation envelope per §4.5.
//
// Wire shape: {ok, data:[BatchItem...], meta:{count, successes, failures}, profile?}.
// Top-level ok = (failures == 0). Per-id ok reflects each item's outcome.
// Even when all items fail, the response stays in success-envelope shape
// (data array, not error envelope) so agents can iterate detail per id.
// profile is the resolved profile name for the invocation; empty string omits the field.
func WriteBatchEnvelope(w io.Writer, items []BatchItem, indent bool, profile string) error {
if items == nil {
items = []BatchItem{}
}
successes, failures := 0, 0
for _, it := range items {
if it.OK {
successes++
} else {
failures++
}
}
env := Envelope{
OK: failures == 0,
Data: items,
Meta: &Meta{
Count: len(items),
Successes: &successes,
Failures: &failures,
},
Notice: GetNotice(),
Profile: profile,
}
return writeJSON(w, env, indent)
}
+104
View File
@@ -0,0 +1,104 @@
package output_test
import (
"bytes"
"strings"
"testing"
"github.com/Tencent/WeKnora/cli/internal/output"
)
func TestWriteBatchEnvelope_AllSuccess(t *testing.T) {
items := []output.BatchItem{
{ID: "id1", OK: true, Result: map[string]string{"deleted_at": "2026-05-20T00:00:00Z"}},
{ID: "id2", OK: true, Result: map[string]string{"deleted_at": "2026-05-20T00:00:00Z"}},
}
var buf bytes.Buffer
if err := output.WriteBatchEnvelope(&buf, items, false, ""); err != nil {
t.Fatalf("unexpected error: %v", err)
}
got := buf.String()
if !strings.Contains(got, `"ok":true`) {
t.Errorf("expected ok:true; got %q", got)
}
if !strings.Contains(got, `"successes":2`) {
t.Errorf("expected successes:2; got %q", got)
}
if !strings.Contains(got, `"count":2`) {
t.Errorf("expected count:2; got %q", got)
}
}
func TestWriteBatchEnvelope_PartialFailure(t *testing.T) {
items := []output.BatchItem{
{ID: "id1", OK: true, Result: map[string]string{"deleted_at": "2026-05-20T00:00:00Z"}},
{ID: "id2", OK: false, Error: &output.ErrDetail{Type: "resource.not_found", Message: "id2 not found"}},
}
var buf bytes.Buffer
if err := output.WriteBatchEnvelope(&buf, items, false, ""); err != nil {
t.Fatalf("unexpected error: %v", err)
}
got := buf.String()
if !strings.Contains(got, `"ok":false`) {
t.Errorf("expected ok:false (partial failure); got %q", got)
}
if !strings.Contains(got, `"successes":1`) || !strings.Contains(got, `"failures":1`) {
t.Errorf("expected counts; got %q", got)
}
if !strings.Contains(got, `"type":"resource.not_found"`) {
t.Errorf("expected per-item error; got %q", got)
}
}
func TestWriteBatchEnvelope_EmptyItems_EmitsEmptyArray(t *testing.T) {
var buf bytes.Buffer
if err := output.WriteBatchEnvelope(&buf, nil, false, ""); err != nil {
t.Fatalf("unexpected: %v", err)
}
got := buf.String()
if strings.Contains(got, `"data":null`) {
t.Errorf("empty items must marshal to [], not null; got %q", got)
}
if !strings.Contains(got, `"data":[]`) {
t.Errorf("expected data:[]; got %q", got)
}
if !strings.Contains(got, `"ok":true`) {
t.Errorf("expected ok:true for empty batch; got %q", got)
}
// count:0 is omitted by omitempty; assert no non-zero count appears.
if strings.Contains(got, `"count":`) {
// If count key is present, it must not be a non-zero value.
if !strings.Contains(got, `"count":0`) {
t.Errorf("count key present but not zero; got %q", got)
}
}
}
func TestWriteBatchEnvelope_AllFail(t *testing.T) {
items := []output.BatchItem{
{ID: "id1", OK: false, Error: &output.ErrDetail{Type: "auth.forbidden", Message: "no perm"}},
{ID: "id2", OK: false, Error: &output.ErrDetail{Type: "resource.not_found", Message: "missing"}},
}
var buf bytes.Buffer
if err := output.WriteBatchEnvelope(&buf, items, false, ""); err != nil {
t.Fatalf("unexpected error: %v", err)
}
got := buf.String()
if !strings.Contains(got, `"ok":false`) {
t.Errorf("expected ok:false; got %q", got)
}
// 全失败仍走 batch envelope shape,不退化到 ErrorEnvelope.
// An ErrorEnvelope has a top-level "error" key alongside "ok"; a batch
// envelope has a top-level "data" array. Check that "data":[ is present.
if !strings.Contains(got, `"data":[`) {
t.Errorf("batch all-fail should still use batch shape (data array), not error envelope; got %q", got)
}
if !strings.Contains(got, `"failures":2`) {
t.Errorf("expected failures:2; got %q", got)
}
// H3b invariant: successes:0 must appear even when all items failed.
// (*int semantics: nil is omitted; &0 is serialized as 0.)
if !strings.Contains(got, `"successes":0`) {
t.Errorf("all-fail batch must emit successes:0 (not omit it); invariant successes+failures==count would be broken; got %q", got)
}
}