Add support for context-only resources (#1405)
Add support for context-only resources
Motivation and Context
#1405
Currently, it is not possible to define a Resource that takes only the Context parameter as an argument. When attempting to create such a resource, the registration logic incorrectly classifies it as a template resource instead of a regular resource.
This limitation prevents developers from creating resources that need access to server session context but don't require dynamic URI components, reducing flexibility in resource design.
How Has This Been Tested?
- [x] Added comprehensive unit tests for context-only resource functionality
- [x] Added integration tests to verify correct resource registration
- [x] All existing resource tests continue to pass (22/22 tests passed)
- [x] Tested with example context-only resource implementation
- [x] Verified backward compatibility with existing resource definitions
Breaking Changes
No breaking changes. The context parameter in Resource.read() method is optional with default None. All existing resource implementations continue to work unchanged.
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
Hi @felixweinberger. Specifically, I wanted to define a simple resource like the one below and display logs within it.
from mcp.server.fastmcp import Context, FastMCP
mcp = FastMCP()
@mcp.resource("resource://user_profile")
def get_user_profile(ctx: Context) -> str:
ctx.info("Fetching user profile")
return "Profile data for user..."
When I tried to display this in Inspector, Inspector mistakenly thought it needed arguments and wouldn't run.
This resource should be recognized as just a Resource, not a template, right?
@felixweinberger Do you have any plans for when it will be merged? Please let me know if there is anything else I can do to help.
I've had success working around this by:
- Adding an
{ignored}template parameter as a URI path element. - Adding an
ignoredfunction parameter to match. - Putting a note in the docstring that the parameter is currently needed due to an implementation quirk and that MCP clients should just always pass zero to it.
Cline has consistently followed that instruction in the docstring, and it's been behaving just like a concrete resource.