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 摘要。