Skip to content

fix(tools): normalize integer arguments - #105

Open
print-happy wants to merge 1 commit into
trpc-group:mainfrom
print-happy:fix
Open

fix(tools): normalize integer arguments#105
print-happy wants to merge 1 commit into
trpc-group:mainfrom
print-happy:fix

Conversation

@print-happy

@print-happy print-happy commented Jun 5, 2026

Copy link
Copy Markdown

Summary

本 PR 在调用工具 handler 前,根据已注册工具的 InputSchema 对 arguments 做归一化:

  • schema 为 integer 的字段会转换为 Go int
  • schema 为 number 的字段保持 float64
  • schema 为 string 的字段保持 string
  • schema 为 boolean 的字段保持 bool
  • schema 为 object / array 的字段保持原结构,并递归处理其中声明为 integer 的子字段
  • schema 未声明的字段保持原始反序列化结果

Problem

用户反馈通过 mcp.WithInteger() 注册工具参数后,在工具 handler 中从req.Params.Arguments 取出的实际类型是 float64,而不是预期的整数类型。

问题发生在 JSON-RPC 请求解析阶段,Go 标准库在反序列化到 interface{} 时,会把 JSON number 默认解成 float64 tools/call 之前直接把 arguments 作为 map[string]interface{} 传给 handler,因此 schema 中声明为 integer 的参数也会以 float64 暴露给用户。

兼容性影响

对存量用户有潜在影响,假设用户之前通过 WithInteger("page") 注册参数,但在 handler 中按旧行为读取,如:

page, ok := req.Params.Arguments["page"].(float64)

升级后该断言会失败。新行为应改为:

page, ok := req.Params.Arguments["page"].(int)

如果用户需要兼容新旧版本,可以临时同时支持两种类型:

switch v := req.Params.Arguments["page"].(type) {
case int:
    page = v
case float64:
    page = int(v)
}

Tests

GOCACHE=/data/tmp/go-build go test -count=1 ./...
GOCACHE=/data/tmp/go-build go vet ./...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant