feat(cli): mcp serve curated stdio MCP server

`weknora mcp serve` — long-lived stdio MCP (Model Context Protocol)
transport that exposes a fixed, curated tool surface to MCP-aware
agents (Claude Desktop, Claude Code, custom MCP clients).

Curated tool set (readonly by default):
- whoami — active context + tenant
- search (hybrid retrieval against a KB)
- kb list / view
- doc list / view
- agent list / view / invoke
- session list / view

The list is intentionally narrow to the read + agent-invoke surface;
destructive verbs (`delete` / `empty` / `upload`) are gated behind
`--write`. Schema is built from each leaf cobra command's flags so
adding a new tool is a single registry entry plus a Service interface.

Includes the simplify post-review polish + a second simplify pass to
fold the resulting feedback (typed schemas, agent_help wording, unify
chat / agent invoke option names).
This commit is contained in:
nullkey
2026-05-14 23:28:14 +08:00
committed by lyingbug
parent 493fc41e98
commit 9bb83b47fd
14 changed files with 1213 additions and 154 deletions
+29 -112
View File
@@ -13,14 +13,15 @@ import (
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/format"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/sse"
sdk "github.com/Tencent/WeKnora/client"
)
// agentInvokeFields enumerates fields surfaced for `--json` discovery on
// `agent invoke`. Matches invokeData below — single-shot result envelope
// with the agent's final answer plus the trace (references, tool calls).
// with the agent's final answer plus the trace (references, tool events).
var agentInvokeFields = []string{
"answer", "references", "tool_calls", "thinking",
"answer", "references", "tool_events", "thinking",
"session_id", "agent_id", "query",
}
@@ -45,25 +46,15 @@ type InvokeService interface {
AgentQAStreamWithRequest(ctx context.Context, sessionID string, req *sdk.AgentQARequest, cb sdk.AgentEventCallback) error
}
// toolCallTrace mirrors a single SSE `tool_call` event so agents can see
// which tools the WeKnora-side agent invoked (and their results). Only the
// fields the server actually emits are captured.
type toolCallTrace struct {
ID string `json:"id"`
Name string `json:"name,omitempty"`
Result string `json:"result,omitempty"`
Data map[string]any `json:"data,omitempty"`
}
// invokeData is the JSON envelope payload.
type invokeData struct {
Answer string `json:"answer"`
References []*sdk.SearchResult `json:"references"`
ToolCalls []toolCallTrace `json:"tool_calls,omitempty"`
Thinking string `json:"thinking,omitempty"`
SessionID string `json:"session_id"`
AgentID string `json:"agent_id"`
Query string `json:"query"`
Answer string `json:"answer"`
References []*sdk.SearchResult `json:"references"`
ToolEvents []sse.AgentToolEvent `json:"tool_events,omitempty"`
Thinking string `json:"thinking,omitempty"`
SessionID string `json:"session_id"`
AgentID string `json:"agent_id"`
Query string `json:"query"`
}
// NewCmdInvoke builds `weknora agent invoke <agent-id> "<text>"`.
@@ -152,12 +143,12 @@ func runInvoke(ctx context.Context, opts *InvokeOptions, jopts *cmdutil.JSONOpti
Channel: "api",
}
acc := newAgentAccumulator()
acc := &sse.AgentAccumulator{}
cb := func(r *sdk.AgentStreamResponse) error {
if streamMode && r != nil && r.ResponseType == sdk.AgentResponseTypeAnswer && r.Content != "" {
_, _ = iostreams.IO.Out.Write([]byte(r.Content))
}
acc.append(r)
acc.Append(r)
return nil
}
@@ -169,7 +160,7 @@ func runInvoke(ctx context.Context, opts *InvokeOptions, jopts *cmdutil.JSONOpti
if errors.Is(streamErr, context.Canceled) || errors.Is(ctx.Err(), context.Canceled) {
return cmdutil.Wrapf(cmdutil.CodeUserAborted, streamErr, "agent invoke cancelled")
}
if acc.answer.Len() > 0 && !acc.done {
if acc.Answer() != "" && !acc.Done() {
return cmdutil.Wrapf(cmdutil.CodeSSEStreamAborted, streamErr, "stream aborted before completion")
}
return cmdutil.WrapHTTP(streamErr, "agent-chat stream")
@@ -177,17 +168,17 @@ func runInvoke(ctx context.Context, opts *InvokeOptions, jopts *cmdutil.JSONOpti
// Server closed cleanly but never sent a Done event — treat as aborted
// so agents don't silently emit a truncated answer as ok=true.
if !acc.done {
if !acc.Done() {
return cmdutil.NewError(cmdutil.CodeSSEStreamAborted, "stream ended without a terminal event")
}
answer := acc.answer.String()
answer := acc.Answer()
if jsonOut {
data := invokeData{
Answer: answer,
References: acc.references,
ToolCalls: acc.toolCalls,
Thinking: acc.thinking.String(),
References: acc.References,
ToolEvents: acc.ToolEvents,
Thinking: acc.Thinking(),
SessionID: sessionID,
AgentID: opts.AgentID,
Query: opts.Query,
@@ -210,98 +201,24 @@ func runInvoke(ctx context.Context, opts *InvokeOptions, jopts *cmdutil.JSONOpti
fmt.Fprintln(out)
}
}
renderToolTrace(out, acc.toolCalls)
renderReferences(out, acc.references)
renderToolTrace(out, acc.ToolEvents)
format.WriteReferences(out, acc.References)
return nil
}
// agentAccumulator buffers an AgentQAStream callback sequence. Distinct
// from internal/sse.Accumulator because the agent event model is wider
// (thinking / tool_call / tool_result / answer / references / reflection /
// error) and uses a flat r.Done bool instead of the
// ResponseType=complete sentinel that KnowledgeQAStream emits.
type agentAccumulator struct {
answer strings.Builder
thinking strings.Builder
references []*sdk.SearchResult
toolCalls []toolCallTrace
done bool
}
func newAgentAccumulator() *agentAccumulator { return &agentAccumulator{} }
func (a *agentAccumulator) append(r *sdk.AgentStreamResponse) {
if r == nil || a.done {
return
}
switch r.ResponseType {
case sdk.AgentResponseTypeAnswer:
if r.Content != "" {
a.answer.WriteString(r.Content)
}
case sdk.AgentResponseTypeThinking, sdk.AgentResponseTypeReflection:
if r.Content != "" {
a.thinking.WriteString(r.Content)
}
case sdk.AgentResponseTypeReferences:
if r.KnowledgeReferences != nil {
a.references = r.KnowledgeReferences
}
case sdk.AgentResponseTypeToolCall, sdk.AgentResponseTypeToolResult:
a.toolCalls = append(a.toolCalls, toolCallTrace{
ID: r.ID,
Name: string(r.ResponseType),
Result: r.Content,
Data: r.Data,
})
}
// References can also arrive on the terminal frame.
if r.KnowledgeReferences != nil && a.references == nil {
a.references = r.KnowledgeReferences
}
if r.Done {
a.done = true
}
}
// renderToolTrace prints a compact tool-call footer in human mode. Skipped
// when the agent invoked no tools — silent beats an empty banner.
func renderToolTrace(w io.Writer, calls []toolCallTrace) {
if len(calls) == 0 {
// renderToolTrace prints a compact tool-event footer in human mode.
// Skipped when the agent emitted no tool events — silent beats an empty
// banner.
func renderToolTrace(w io.Writer, events []sse.AgentToolEvent) {
if len(events) == 0 {
return
}
fmt.Fprintln(w)
fmt.Fprintln(w, "──── Tool trace ────")
for i, c := range calls {
fmt.Fprintf(w, "[%d] %s", i+1, c.Name)
if c.Result != "" {
fmt.Fprintf(w, " %s", truncateInline(c.Result, 80))
}
fmt.Fprintln(w)
}
}
// renderReferences mirrors chat.go's references footer for parity.
func renderReferences(w io.Writer, refs []*sdk.SearchResult) {
if len(refs) == 0 {
return
}
fmt.Fprintln(w)
fmt.Fprintln(w, "──── References ────")
for i, r := range refs {
if r == nil {
continue
}
title := r.KnowledgeTitle
if title == "" {
title = r.KnowledgeFilename
}
if title == "" {
title = r.KnowledgeID
}
fmt.Fprintf(w, "[%d] %s", i+1, title)
if r.Score > 0 {
fmt.Fprintf(w, " score=%.3f", r.Score)
for i, e := range events {
fmt.Fprintf(w, "[%d] %s", i+1, e.Kind)
if e.Result != "" {
fmt.Fprintf(w, " %s", truncateInline(e.Result, 80))
}
fmt.Fprintln(w)
}
+5 -5
View File
@@ -150,7 +150,7 @@ func (c *createSessionTracker) CreateSession(ctx context.Context, req *sdk.Creat
return c.InvokeService.CreateSession(ctx, req)
}
func TestInvoke_ToolCallsCaptured(t *testing.T) {
func TestInvoke_ToolEventsCaptured(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &scriptedInvokeSvc{events: []*sdk.AgentStreamResponse{
toolCallEvent("call_1", "knowledge_search"),
@@ -167,11 +167,11 @@ func TestInvoke_ToolCallsCaptured(t *testing.T) {
if err := json.Unmarshal(out.Bytes(), &env); err != nil {
t.Fatalf("parse: %v", err)
}
if len(env.Data.ToolCalls) != 1 {
t.Fatalf("expected 1 tool call, got %d", len(env.Data.ToolCalls))
if len(env.Data.ToolEvents) != 1 {
t.Fatalf("expected 1 tool call, got %d", len(env.Data.ToolEvents))
}
if env.Data.ToolCalls[0].ID != "call_1" {
t.Errorf("tool_calls[0].id = %q, want call_1", env.Data.ToolCalls[0].ID)
if env.Data.ToolEvents[0].ID != "call_1" {
t.Errorf("tool_calls[0].id = %q, want call_1", env.Data.ToolEvents[0].ID)
}
}
+1 -30
View File
@@ -23,7 +23,6 @@ import (
"context"
"errors"
"fmt"
"io"
"strings"
"github.com/spf13/cobra"
@@ -258,37 +257,9 @@ func runChat(ctx context.Context, opts *Options, jopts *cmdutil.JSONOptions, svc
fmt.Fprintln(out)
}
}
renderReferences(out, references)
format.WriteReferences(out, references)
return nil
}
// renderReferences prints a compact human-readable references block.
// Skipped entirely when the server returned no references — agent-friendly
// silence beats an empty banner.
func renderReferences(w io.Writer, refs []*sdk.SearchResult) {
if len(refs) == 0 {
return
}
fmt.Fprintln(w)
fmt.Fprintln(w, "──── References ────")
for i, r := range refs {
if r == nil {
continue
}
title := r.KnowledgeTitle
if title == "" {
title = r.KnowledgeFilename
}
if title == "" {
title = r.KnowledgeID
}
fmt.Fprintf(w, "[%d] %s", i+1, title)
if r.Score > 0 {
fmt.Fprintf(w, " score=%.3f", r.Score)
}
fmt.Fprintln(w)
}
}
// compile-time check: the production SDK client implements chatService.
var _ chatService = (*sdk.Client)(nil)
+40
View File
@@ -0,0 +1,40 @@
// Package mcpcmd holds the `weknora mcp` command tree.
//
// MCP (Model Context Protocol; https://spec.modelcontextprotocol.io/) is the
// JSON-RPC 2.0 wire protocol agentic IDEs (Claude Code, Cursor, Continue,
// Zed) and runtimes (Anthropic Reference, Stripe MCP) use to call external
// tools. `weknora mcp serve` exposes a curated subset of the CLI's read
// surface as MCP tools so an IDE-side agent can list / view / search / chat
// against the user's active WeKnora context without shelling out to the CLI
// per call.
//
// Package name is `mcpcmd` to avoid shadowing `cli/internal/mcp` (the
// transport-and-handlers implementation). Same naming hygiene as
// `agentcmd` / `sessioncmd`.
package mcpcmd
import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
)
// NewCmd builds the `weknora mcp` parent. Called from cli/cmd/root.go.
func NewCmd(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "mcp",
Short: "Run weknora as a Model Context Protocol server",
Long: `Exposes weknora's read surface as MCP tools so agentic IDE clients
(Claude Code, Cursor, Continue, Zed) can call them over JSON-RPC.
Initial tool surface is read-only and curated: kb_list / kb_view /
doc_list / doc_view / doc_download / search_chunks / chat / agent_list /
agent_invoke. Destructive verbs (create / delete / upload) are deliberately
excluded — the agent should ask the user before mutating; the CLI's
exit-10 protocol covers that path.`,
Args: cobra.NoArgs,
Run: func(c *cobra.Command, _ []string) { _ = c.Help() },
}
cmd.AddCommand(NewCmdServe(f))
return cmd
}
+47
View File
@@ -0,0 +1,47 @@
package mcpcmd
import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/agent"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
mcpserver "github.com/Tencent/WeKnora/cli/internal/mcp"
)
// NewCmdServe builds `weknora mcp serve`. Currently stdio-only; HTTP
// (streamable / SSE) is roadmap 5-7.
func NewCmdServe(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "serve",
Short: "Run an MCP server over stdio",
Long: `Speaks JSON-RPC 2.0 on stdin/stdout to an MCP client. Logs go to
stderr; the data channel is reserved for protocol traffic.
Authentication is inherited from the active context (or --context). The
server eagerly resolves the SDK client at startup — if no context is
configured, the process exits with auth.unauthenticated before any MCP
handshake. This way an IDE-side agent sees a clear failure mode rather
than a server that handshakes successfully then errors on every tool.
To use with Claude Code, add to ~/.claude/mcp_servers.json:
{
"weknora": {
"command": "weknora",
"args": ["mcp", "serve"]
}
}`,
Args: cobra.NoArgs,
RunE: func(c *cobra.Command, _ []string) error {
// Eagerly construct the SDK client. Surfaces auth /
// configuration problems before any MCP handshake.
cli, err := f.Client()
if err != nil {
return err
}
return mcpserver.RunStdio(c.Context(), cli)
},
}
agent.SetAgentHelp(cmd, "Long-lived stdio MCP server. Reads JSON-RPC requests from stdin, writes responses to stdout, logs to stderr. Surfaces 9 read-only tools (kb_list/kb_view/doc_list/doc_view/doc_download/search_chunks/chat/agent_list/agent_invoke); destructive verbs are intentionally excluded. Auth is inherited from the active context — to switch, exit and re-launch with --context. Long tools (chat / agent_invoke) accumulate the LLM stream server-side and return a single CallToolResult — no MCP streaming-content extension, per spec 2025-06-18 (tools.mdx).")
return cmd
}
+2
View File
@@ -17,6 +17,7 @@ import (
"github.com/Tencent/WeKnora/cli/cmd/doctor"
"github.com/Tencent/WeKnora/cli/cmd/kb"
linkcmd "github.com/Tencent/WeKnora/cli/cmd/link"
mcpcmd "github.com/Tencent/WeKnora/cli/cmd/mcp"
"github.com/Tencent/WeKnora/cli/cmd/search"
sessioncmd "github.com/Tencent/WeKnora/cli/cmd/session"
"github.com/Tencent/WeKnora/cli/internal/agent"
@@ -177,6 +178,7 @@ hybrid searches against a WeKnora server from your shell or an AI agent.`,
cmd.AddCommand(chatcmd.NewCmd(f))
cmd.AddCommand(sessioncmd.NewCmd(f))
cmd.AddCommand(agentcmd.NewCmd(f))
cmd.AddCommand(mcpcmd.NewCmd(f))
return cmd
}
+9 -1
View File
@@ -119,7 +119,15 @@ func runList(ctx context.Context, opts *ListOptions, jopts *cmdutil.JSONOptions,
}
if jopts.Enabled() {
meta := &format.Meta{HasMore: opts.Page*opts.PageSize < total}
// When --since is active, has_more is meaningless: the server's
// total counts all sessions but the page is now client-side
// filtered. An agent walking pages would see has_more=true even
// when no later page can contain matching items. Drop the flag
// rather than mislead. The agent_help string documents this.
meta := &format.Meta{}
if since == 0 {
meta.HasMore = opts.Page*opts.PageSize < total
}
return format.WriteEnvelopeFiltered(
iostreams.IO.Out,
format.Success(listResult{Items: items}, meta),