modelcontextprotocol / modelcontextprotocol/python-sdk

Expose `schema_generator` on `FastMCP` for tool params schema generation

未关闭
#2,582 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

enhancement needs decision P3
主要语言
Python
星标
24.3k
派生
4k
平均合并
1 天 1 小时
30 天内合并 PR
31

描述

Description
Context

Tool.from_function (in src/mcp/server/fastmcp/tools/base.py) generates the
tool parameters JSON schema via:

parameters = func_arg_metadata.arg_model.model_json_schema(by_alias=True)

This is hardcoded — no way for users to customize the generation. Pydantic 2.11+
supports union_format='primitive_type_array' which produces compact
LLM-friendly schemas like {"type": ["integer", "string"]} instead of
{"anyOf": [...]}. There's no path to enable it without monkey-patching or
post-processing.

Proposal

Add schema_generator: type[GenerateJsonSchema] | None = None to FastMCP.__init__.
When provided, plumb it to both model_json_schema calls:

# tools/base.py
parameters = func_arg_metadata.arg_model.model_json_schema(
    by_alias=True,
    schema_generator=self.schema_generator or GenerateJsonSchema,
)

# utilities/func_metadata.py
schema = model.model_json_schema(
    schema_generator=self.schema_generator or StrictJsonSchema,
)
Use case
from pydantic.json_schema import GenerateJsonSchema

class CompactUnionGen(GenerateJsonSchema):
    def __init__(self, by_alias=True, ref_template='#/$defs/{model}'):
        super().__init__(
            by_alias=by_alias,
            ref_template=ref_template,
            union_format='primitive_type_array',
        )

mcp = FastMCP("srv", schema_generator=CompactUnionGen)
Tradeoff to discuss

func_metadata.py currently uses StrictJsonSchema (warnings → errors). With a
user-supplied generator, strict semantics are lost unless the user extends
StrictJsonSchema themselves. Proposed resolution: document that custom
generators should extend StrictJsonSchema if strict output validation is
desired.

Backward compat

Default None preserves current behavior exactly.

References

No response

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

从 src/mcp/server/fastmcp/tools/base.py 和 utilities/func_metadata.py 开始,然后跟踪 FastMCP.init 的值如何传递到两处 model_json_schema 调用。添加可选的 schema_generator 并使其到达两条路径、默认值保持当前行为,以及按提议记录或覆盖 strict-schema 的权衡后,此更改即完成。

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
backend-api-design
Issue 类型
功能
难度
3/5
预计耗时
1-2 天
活跃度
冷清
描述清晰度
基本清楚
新手友好度
55/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。