fix: enables context injection into resources
rebase of https://github.com/modelcontextprotocol/python-sdk/pull/248 (copied below)
closes https://github.com/modelcontextprotocol/python-sdk/issues/244
Motivation and Context
According to the readme it should be possible to pass a Context to a resource (like it is for tools), but that's currently throwing an error (https://github.com/modelcontextprotocol/python-sdk/issues/244)
How Has This Been Tested?
How Has This Been Tested?
Added tests, and confirmed with inspector that the below demo server works as intended:
from mcp.server.fastmcp import FastMCP, Context
mcp = FastMCP("Demo")
@mcp.resource("identification://{name}")
def get_ids(name: str, ctx: Context) -> str:
request_id = ctx.request_id
client_id = ctx.client_id
return str(f"{request_id},{client_id}")
Breaking Changes
Types of changes
- [x] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing functionality to change)
- [ ] Documentation update
Checklist
- [x] I have read the MCP Documentation
- [x] My code follows the repository's style guidelines
- [x] New and existing tests pass locally
- [x] I have added appropriate error handling
- [x] I have added or updated documentation as needed
Additional context
I tried to follow a similar structure to the way context is injected in tools
context injection into prompts would be great also
It would be fantastic with this feature! Since most of my endpoints use context, I currently have to wrap them all as tools.
This PR doesn't seem to be enough. We can't read from the ctx on the resource yet... All the tests are receiving the Context, but they are actually not using it. 😅
There seems to be some complexity in how that interacts with the concept of concrete/direct resources vs resource templates. In particular, a resource function might accept only a Context param (for example, if it lists all objects that a user can access). I think this PR would cause those to appear as nullary (0-arg) resource templates, which seem to be an edge case for clients (e.g. at first glance, they don't seem to work properly in the MCP Inspector).
Reading through the code, it appears that concrete resources are already lazy - so we could consider Context-only resources as concrete/direct and thread through the context in the read method.
This looks to be the same / similar issue as being tackled by #1406. Closing this one in favor of consolidating on the active discussion.