feat(cli): MCP Tool.Annotations on 10 tools (spec 2025-06-18)

Bumps modelcontextprotocol/go-sdk to v1.6.1 and populates Tool.Annotations
on every registered MCP tool per the per-tool hint table:

  Read tools (8):   destructiveHint=false, readOnlyHint=true,
                    idempotentHint=true,   openWorldHint=false
  Invoke tools (2): destructiveHint=false, readOnlyHint=false,
                    idempotentHint=false,  openWorldHint=true

Invoke-class tools (chat, agent_invoke) carry openWorldHint=true because
the server may dispatch external skills (web_search etc.). Read tools are
sealed: idempotent + read-only + closed-world.

TestToolAnnotations_AllToolsHaveExpectedHints asserts the matrix so any
future drift surfaces in CI rather than at first client integration.
This commit is contained in:
nullkey
2026-05-28 04:28:10 +08:00
committed by lyingbug
parent 7b2ef8bd8e
commit c11df51c79
4 changed files with 156 additions and 9 deletions
+1 -1
View File
@@ -8,7 +8,7 @@ require (
github.com/itchyny/gojq v0.12.19
github.com/mattn/go-isatty v0.0.22
github.com/mattn/go-runewidth v0.0.23
github.com/modelcontextprotocol/go-sdk v1.6.0
github.com/modelcontextprotocol/go-sdk v1.6.1
github.com/spf13/cobra v1.10.2
github.com/spf13/pflag v1.0.10
github.com/stretchr/testify v1.11.1
+2 -2
View File
@@ -75,8 +75,8 @@ github.com/mattn/go-runewidth v0.0.23 h1:7ykA0T0jkPpzSvMS5i9uoNn2Xy3R383f9HDx3Ry
github.com/mattn/go-runewidth v0.0.23/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
github.com/mitchellh/hashstructure/v2 v2.0.2 h1:vGKWl0YJqUNxE8d+h8f6NJLcCJrgbhC4NcD46KavDd4=
github.com/mitchellh/hashstructure/v2 v2.0.2/go.mod h1:MG3aRVU/N29oo/V/IhBX8GR/zz4kQkprJgF2EVszyDE=
github.com/modelcontextprotocol/go-sdk v1.6.0 h1:PPLS3kn7WtOEnR+Af4X5H96SG0qSab8R/ZQT/HkhPkY=
github.com/modelcontextprotocol/go-sdk v1.6.0/go.mod h1:kzm3kzFL1/+AziGOE0nUs3gvPoNxMCvkxokMkuFapXQ=
github.com/modelcontextprotocol/go-sdk v1.6.1 h1:0zOSupjKUxPKSocPT1Wtago+mUHU2/uZ4xSOY0FGReU=
github.com/modelcontextprotocol/go-sdk v1.6.1/go.mod h1:kzm3kzFL1/+AziGOE0nUs3gvPoNxMCvkxokMkuFapXQ=
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI=
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo=
github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
+83 -6
View File
@@ -110,12 +110,13 @@ type agentInvokeService interface {
// 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.
// TODO: 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)
@@ -141,6 +142,13 @@ 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.",
Annotations: &mcpsdk.ToolAnnotations{
Title: "List Knowledge Bases",
DestructiveHint: bptr(false),
ReadOnlyHint: true,
IdempotentHint: true,
OpenWorldHint: bptr(false),
},
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, _ kbListInput) (*mcpsdk.CallToolResult, any, error) {
items, err := svc.ListKnowledgeBases(ctx)
if err != nil {
@@ -163,6 +171,13 @@ 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.",
Annotations: &mcpsdk.ToolAnnotations{
Title: "View Knowledge Base",
DestructiveHint: bptr(false),
ReadOnlyHint: true,
IdempotentHint: true,
OpenWorldHint: bptr(false),
},
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, in kbViewInput) (*mcpsdk.CallToolResult, any, error) {
if in.KBID == "" {
return toolErrorResult(cmdutil.NewError(cmdutil.CodeKBIDRequired, "kb_id is required")), nil, nil
@@ -201,6 +216,13 @@ 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.",
Annotations: &mcpsdk.ToolAnnotations{
Title: "List Documents",
DestructiveHint: bptr(false),
ReadOnlyHint: true,
IdempotentHint: true,
OpenWorldHint: bptr(false),
},
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, in docListInput) (*mcpsdk.CallToolResult, any, error) {
if in.KBID == "" {
return toolErrorResult(cmdutil.NewError(cmdutil.CodeKBIDRequired, "kb_id is required")), nil, nil
@@ -258,6 +280,13 @@ 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.).",
Annotations: &mcpsdk.ToolAnnotations{
Title: "View Document",
DestructiveHint: bptr(false),
ReadOnlyHint: true,
IdempotentHint: true,
OpenWorldHint: bptr(false),
},
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, in docViewInput) (*mcpsdk.CallToolResult, any, error) {
if in.DocID == "" {
return toolErrorResult(cmdutil.NewError(cmdutil.CodeInputMissingFlag, "doc_id is required")), nil, nil
@@ -297,6 +326,13 @@ 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).",
Annotations: &mcpsdk.ToolAnnotations{
Title: "Download Document",
DestructiveHint: bptr(false),
ReadOnlyHint: true,
IdempotentHint: true,
OpenWorldHint: bptr(false),
},
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, in docDownloadInput) (*mcpsdk.CallToolResult, any, error) {
if in.DocID == "" {
return toolErrorResult(cmdutil.NewError(cmdutil.CodeInputMissingFlag, "doc_id is required")), nil, nil
@@ -349,6 +385,13 @@ func addSearchChunks(server *mcpsdk.Server, svc knowledgeService) {
mcpsdk.AddTool(server, &mcpsdk.Tool{
Name: "search_chunks",
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.",
Annotations: &mcpsdk.ToolAnnotations{
Title: "Search Knowledge Chunks",
DestructiveHint: bptr(false),
ReadOnlyHint: true,
IdempotentHint: true,
OpenWorldHint: bptr(false),
},
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, in searchChunksInput) (*mcpsdk.CallToolResult, any, error) {
if in.KBID == "" {
return toolErrorResult(cmdutil.NewError(cmdutil.CodeKBIDRequired, "kb_id is required")), nil, nil
@@ -404,6 +447,13 @@ 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 (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.",
Annotations: &mcpsdk.ToolAnnotations{
Title: "Chat with KB (Streaming RAG)",
DestructiveHint: bptr(false),
ReadOnlyHint: false,
IdempotentHint: false,
OpenWorldHint: bptr(true),
},
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, in chatInput) (*mcpsdk.CallToolResult, any, error) {
if in.KBID == "" {
return toolErrorResult(cmdutil.NewError(cmdutil.CodeKBIDRequired, "kb_id is required")), nil, nil
@@ -464,6 +514,13 @@ 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.",
Annotations: &mcpsdk.ToolAnnotations{
Title: "List Custom Agents",
DestructiveHint: bptr(false),
ReadOnlyHint: true,
IdempotentHint: true,
OpenWorldHint: bptr(false),
},
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, _ agentListInput) (*mcpsdk.CallToolResult, any, error) {
items, err := svc.ListAgents(ctx)
if err != nil {
@@ -498,6 +555,13 @@ 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 (MCP tools/call has no standard partial-response, so this is NOT streaming); the tool returns the final accumulated response once the stream completes.",
Annotations: &mcpsdk.ToolAnnotations{
Title: "Invoke Custom Agent",
DestructiveHint: bptr(false),
ReadOnlyHint: false,
IdempotentHint: false,
OpenWorldHint: bptr(true),
},
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, in agentInvokeInput) (*mcpsdk.CallToolResult, any, error) {
if in.AgentID == "" {
return toolErrorResult(cmdutil.NewError(cmdutil.CodeInputMissingFlag, "agent_id is required")), nil, nil
@@ -570,6 +634,13 @@ 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.",
Annotations: &mcpsdk.ToolAnnotations{
Title: "List Knowledge Chunks",
DestructiveHint: bptr(false),
ReadOnlyHint: true,
IdempotentHint: true,
OpenWorldHint: bptr(false),
},
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, in chunkListInput) (*mcpsdk.CallToolResult, any, error) {
if in.DocID == "" {
return toolErrorResult(cmdutil.NewError(cmdutil.CodeInputMissingFlag, "doc_id is required")), nil, nil
@@ -616,3 +687,9 @@ func encodeDownload(buf []byte) (string, bool) {
}
return string(buf), false
}
// bptr returns a pointer to a bool literal. MCP ToolAnnotations uses
// pointer types for DestructiveHint and OpenWorldHint so that "explicit
// false" can be distinguished from "field omitted (default true per MCP
// spec 2025-06-18)".
func bptr(b bool) *bool { return &b }
+70
View File
@@ -584,3 +584,73 @@ func TestTool_ChunkList_NonNumericLimit(t *testing.T) {
require.NoError(t, err)
require.True(t, res.IsError, "expected IsError=true when limit is a string")
}
// derefBool is the test-side counterpart to bptr: ToolAnnotations uses
// *bool for DestructiveHint/OpenWorldHint to distinguish "unset" from
// "false", but assertions here treat unset as false (a nil pointer means
// the field was omitted from the JSON wire envelope, which clients should
// read as the documented default).
func derefBool(p *bool) bool {
if p == nil {
return false
}
return *p
}
// TestToolAnnotations_AllToolsHaveExpectedHints locks the per-tool hint
// table. Each of the 10 registered tools must surface the exact
// DestructiveHint / ReadOnlyHint / IdempotentHint / OpenWorldHint + Title
// values shown below. This guards against silent drift during future
// refactors (e.g. someone marking chat as readOnly, or an invoke tool as
// closed-world).
//
// Note on plain-bool fields: ReadOnlyHint and IdempotentHint are bool
// (not *bool) with `omitempty`. For invoke-class tools that explicitly set
// them to false in the builder, the JSON envelope omits the field and the
// client-side decode surfaces the zero value (false), which matches the
// table.
func TestToolAnnotations_AllToolsHaveExpectedHints(t *testing.T) {
expected := map[string]struct {
destructive bool
readOnly bool
idempotent bool
openWorld bool
title string
}{
"kb_list": {destructive: false, readOnly: true, idempotent: true, openWorld: false, title: "List Knowledge Bases"},
"kb_view": {destructive: false, readOnly: true, idempotent: true, openWorld: false, title: "View Knowledge Base"},
"doc_list": {destructive: false, readOnly: true, idempotent: true, openWorld: false, title: "List Documents"},
"doc_view": {destructive: false, readOnly: true, idempotent: true, openWorld: false, title: "View Document"},
"doc_download": {destructive: false, readOnly: true, idempotent: true, openWorld: false, title: "Download Document"},
"search_chunks": {destructive: false, readOnly: true, idempotent: true, openWorld: false, title: "Search Knowledge Chunks"},
"chat": {destructive: false, readOnly: false, idempotent: false, openWorld: true, title: "Chat with KB (Streaming RAG)"},
"agent_list": {destructive: false, readOnly: true, idempotent: true, openWorld: false, title: "List Custom Agents"},
"agent_invoke": {destructive: false, readOnly: false, idempotent: false, openWorld: true, title: "Invoke Custom Agent"},
"chunk_list": {destructive: false, readOnly: true, idempotent: true, openWorld: false, title: "List Knowledge Chunks"},
}
c, _ := newTestServer(t, &fakeSvc{})
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
res, err := c.ListTools(ctx, nil)
require.NoError(t, err, "ListTools must succeed")
got := map[string]*mcpsdk.Tool{}
for _, tool := range res.Tools {
got[tool.Name] = tool
}
for name, want := range expected {
t.Run(name, func(t *testing.T) {
tool, ok := got[name]
require.True(t, ok, "tool %q not registered", name)
require.NotNil(t, tool.Annotations, "tool %q must set Annotations", name)
a := tool.Annotations
assert.Equal(t, want.title, a.Title, "Title")
assert.Equal(t, want.destructive, derefBool(a.DestructiveHint), "DestructiveHint")
assert.Equal(t, want.readOnly, a.ReadOnlyHint, "ReadOnlyHint")
assert.Equal(t, want.idempotent, a.IdempotentHint, "IdempotentHint")
assert.Equal(t, want.openWorld, derefBool(a.OpenWorldHint), "OpenWorldHint")
})
}
}