A resource template value that fails the handler's type hint is logged as a crash and answered -32603
维护者通常 1 天内回复
评估
调研方向
Start with src/mcp/server/mcpserver/resources/templates.py, especially ResourceTemplate.from_function and ResourceTemplate.create_resource, then review the related discussion in #3314 and the linked pull request #3841. Check the resource template tests and the type conversion section in docs/servers/uri-templates.md. Done means invalid URI parameters produce the expected unknown resource response while handler body validation errors remain unexpected errors; resolve the validation and template matching questions raised in the issue.
由索引模型根据 Issue 内容生成。
描述
Initial Checks
- I confirm that I'm using the newest release of my line (the latest 2.x, or the latest 1.x if I'm still on v1)
- I confirm that I searched for my issue in https://github.com/modelcontextprotocol/python-sdk/issues before opening this issue
Release line
2.x (current stable)
Description
A resource template handler can take a parameter with a non-str annotation, such as user_id: int. The "Type conversion" section of docs/servers/uri-templates.md teaches this with orders://{order_id}. When a URI carries a value that doesn't convert, the SDK treats it as a server crash. Reading users://abc/profile returns -32603 Error creating resource from template users://abc/profile, and the server logs Resource 'users://abc/profile' raised an unexpected exception at ERROR with the full pydantic ValidationError traceback. Any client can trigger this, and it happens on every such request.
Expected: that URI names no resource, so it should get the same answer as an unmatched URI or a path-safety rejection: -32602 Unknown resource: users://abc/profile, logged once at INFO. Tools already treat a schema rejection as anticipated (one INFO line, no traceback).
Cause: ResourceTemplate.from_function (src/mcp/server/mcpserver/resources/templates.py) wraps the handler in validate_call, so validating the URI parameters and running the body happen in one call. In ResourceTemplate.create_resource, the ValidationError from a bad parameter lands in except Exception and becomes UnexpectedResourceError. #3314 lists this under "Not in here": "A resource template parameter that fails its type annotation is still logged as a crash: templates run through validate_call, which fuses validation with the call. Not a regression. Follow-up." No issue tracks it yet.
Proposed fix: from_function already builds the handler's argument model with func_metadata. Keep it on the template as a private attribute and, inside the existing try of create_resource, validate the extracted parameters against it before calling the handler, raising ResourceNotFoundError(f"Unknown resource: {uri}") on failure. A ValidationError from the handler body, or a validator raising something other than ValueError/AssertionError, stays a crash. I have this on a local branch (about 20 lines, two tests and one docs sentence) and would like to send the PR if the direction works for you.
Two choices I'd like your view on:
- The parameters are validated twice (here and again by
validate_call), so a custom validator runs twice per read, and a stateful one that passes the first time and fails the second surfaces as a crash. Validating once means calling the undecorated function with the model's output, which either changes what the publicResourceTemplate.fnholds or keeps a second, private reference to the function. ReusingFuncMetadata.validate_arguments()asTool.rundoes would also add itspre_parse_jsonstep, which JSON-decodes string values for non-strparameters. - Like the path-safety check, a value that fails stops at the first matching template. With
items://{item_id}/x(item_id: int) registered beforeitems://{slug}/x,items://hello/xgets-32602and does not fall through to the second template. Should it fall through instead?
Disclosure: Claude Code found this, wrote the fix and tests, ran the example and drafted this issue; I reviewed the output on main and on the branch, and the duplicate search, before filing.
Example Code
import anyio
from mcp import Client, MCPError
from mcp.server import MCPServer
mcp = MCPServer("repro")
@mcp.resource("users://{user_id}/profile")
def profile(user_id: int) -> str:
return f"user {user_id}"
async def main() -> None:
async with Client(mcp) as client:
print((await client.read_resource("users://42/profile")).contents[0].text)
try:
await client.read_resource("users://abc/profile")
except MCPError as e:
print(e.error.code, e.error.message)
anyio.run(main)
# user 42
# -32603 Error creating resource from template users://abc/profile
# stderr: ERROR Resource 'users://abc/profile' raised an unexpected exception
# + the pydantic ValidationError traceback (int_parsing, input_value='abc')
Python & MCP Python SDK
Python 3.11.14, pydantic 2.12.5, macOS
mcp main at 77001c9. src/mcp/server/mcpserver/resources/templates.py is unchanged since v2.3.0 (2118f14).
- 主要语言
- Python
- 星标
- 25k
- 派生
- 4.2k
- 平均合并
- 10 分钟
- 30 天内合并 PR
- 1
环境准备
- 没有 Dockerfile 或 Docker Compose 文件
- 有 Pull Request 模板
- 阅读贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
modelcontextprotocol/python-sdk 的其他 Issue
-
v2
难度 1/5 1 小时以内 新手友好度 86/100
modelcontextprotocol/python-sdk#3978 · 2 条评论 ·
维护者通常 1 天内回复
-
Client serves cached tools after its context exits with an exception可能已有人在做 @jonxsong 于 1 天前认领。 未关闭
难度 2/5 1-3 小时 新手友好度 65/100
modelcontextprotocol/python-sdk#3968 · 1 条评论 ·
维护者通常 1 天内回复
-
难度 2/5 1-3 小时 新手友好度 85/100
modelcontextprotocol/python-sdk#3957 ·
维护者通常 1 天内回复
-
v2
难度 1/5 1 小时以内 新手友好度 91/100
modelcontextprotocol/python-sdk#3934 · 2 条评论 ·
维护者通常 1 天内回复
-
bug v1
难度 2/5 1-3 小时 新手友好度 79/100
modelcontextprotocol/python-sdk#3929 · 2 条评论 ·
维护者通常 1 天内回复
查看 modelcontextprotocol/python-sdk 的全部 Issue
相似的 Issue
-
auto-reported bug
难度 2/5 1-3 小时 新手友好度 62/100
维护者通常 1 天内回复
-
难度 2/5 1-3 小时 新手友好度 76/100
-
backend bug
难度 2/5 1-3 小时 新手友好度 86/100
nolte/kamerplanter#3193 ·
维护者通常 1 天内回复
-
soup prune-prompt exits 1 after writing its output on a file over 100,000 rows, and reports a capped row count otherwise可能已有人在做 @abdulwaarith0 今天认领。 未关闭needs-triage
难度 2/5 1-3 小时 新手友好度 84/100
MakazhanAlpamys/Soup#3690 · 1 条评论 ·
维护者通常 1 天内回复
-
难度 2/5 1-3 小时 新手友好度 78/100
维护者通常 1 天内回复