Skip to content

Conversation

SamMorrowDrums
Copy link
Contributor

@SamMorrowDrums SamMorrowDrums commented Mar 18, 2025

Closes: #53

May help with: #51

This PR adds support for conformant templates, and also provides the parameters to the handler, as sometimes the backend for a resource might actually be an API call with params rather than a static file or similar.

The current resource read does not handle templates according to RFC 6570 which makes it impossible to implement certain dynamic resource URIs. This support is specified in the specification for template resources for the Model Context Protocol.

I hope the contribution is welcome, and introducing a dependency isn't considered too extreme in the circumstances, but obviously I hope one way or another we can do this in a way that pleases everyone. I discovered this while implementing a resource template and found I was unable to do it with nested dynamic resources.

Thanks for the awesome work.

Summary by CodeRabbit

  • New Features

    • Enhanced resource template processing now delivers more robust URI pattern matching and precise parameter extraction during resource handling.
  • Tests

    • Added new automated tests to validate resource template functionality, ensuring improved reliability and consistent behavior.

Copy link
Contributor

coderabbitai bot commented Mar 18, 2025

Walkthrough

The changes update the handling of URI templates to support RFC 6570. A new indirect dependency (github.com/yosida95/uritemplate/v3 v3.0.2) is introduced in go.mod. The code in mcp/resources.go and mcp/types.go now utilizes the uritemplate package, converting the URI template field from a string to a structured pointer type, and calling uritemplate.MustNew for processing. In server/server.go, functions are modified to use the new template type and methods, and a corresponding test is added in server/server_test.go to validate these changes.

Changes

Files Change Summary
go.mod Added an indirect dependency: github.com/yosida95/uritemplate/v3 v3.0.2.
mcp/resources.go, mcp/types.go Added import for uritemplate, updated URITemplate processing in NewResourceTemplate (using uritemplate.MustNew), and changed the URITemplate field in ResourceTemplate from a string to a pointer type.
server/server.go Modified AddResourceTemplate, handleReadResource, and matchesTemplate to use the pointer to uritemplate.Template and its methods, ensuring raw template values and parameter extraction are correctly handled.
server/server_test.go Added TestMCPServer_ResourceTemplates to validate resource template addition, matching, and parameter extraction from the URITemplate.

Assessment against linked issues

Objective Addressed Explanation
Support RFC 6570 for Resource Templates (#53)

Tip

⚡🧪 Multi-step agentic review comment chat (experimental)
  • We're introducing multi-step agentic chat in review comments. This experimental feature enhances review discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments.
    - To enable this feature, set early_access to true under in the settings.

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a73d7cf and 8a5b4bb.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (5)
  • go.mod (1 hunks)
  • mcp/resources.go (2 hunks)
  • mcp/types.go (2 hunks)
  • server/server.go (4 hunks)
  • server/server_test.go (1 hunks)
🧰 Additional context used
🧬 Code Definitions (2)
server/server_test.go (2)
mcp/types.go (8) (8)
  • ReadResourceRequest (365:374)
  • ResourceContents (466:468)
  • Params (43:43)
  • TextResourceContents (470:478)
  • TextResourceContents (480:480)
  • JSONRPCResponse (137:141)
  • Result (112:116)
  • ReadResourceResult (378:381)
mcp/utils.go (2) (2)
  • result (492:492)
  • result (570:570)
server/server.go (2)
testdata/mockstdio_server.go (1) (1)
  • request (30:30)
mcp/types.go (1) (1)
  • Params (43:43)
🔇 Additional comments (10)
go.mod (1)

13-13: Dependency added for RFC 6570 URI template support

The addition of github.com/yosida95/uritemplate/v3 as an indirect dependency provides support for RFC 6570 URI templates, which is essential for implementing dynamic resource URIs as mentioned in the PR objectives.

mcp/resources.go (2)

3-3: Import added for URI template support

Adding the uritemplate package is necessary for the RFC 6570 implementation.


65-65:

✅ Verification successful

Using structured URI template in place of string

The change from storing the raw string to using a parsed uritemplate.Template object improves validation and will help with template variable extraction.

One note: using MustNew will panic if given an invalid template. This is acceptable for initialization code but be cautious if using with externally-provided templates in the future.

Consider verifying that invalid template strings are handled gracefully in user-facing contexts:


🏁 Script executed:

#!/bin/bash
# Look for any error handling around uritemplate.MustNew or uritemplate.New
rg "uritemplate\.(MustNew|New)" -A 3 -B 3

Length of output: 455


Attention: Structured URI Template Initialization

Transforming the raw URI template string into a parsed uritemplate.Template object indeed improves validation and aids in extracting template variables. Our verification using the search for uritemplate.MustNew confirms that this function is used solely during initialization and that no additional error handling exists—this is acceptable given that invalid templates immediately raise a panic in this context. No changes are required unless these templates eventually originate from external sources.

server/server_test.go (1)

780-835: Well-structured test for new URI template functionality

This test thoroughly verifies the RFC 6570 support implementation by:

  1. Creating a resource template with URI pattern variables ({a} and {/b*})
  2. Validating parameter extraction in the handler function
  3. Confirming that the correct response is returned

The test covers both simple substitution ({a}) and more complex path-style parameters ({/b*}), which is a good test of the RFC 6570 functionality.

mcp/types.go (2)

5-9: Import statement added for URI template support

The import of the uritemplate package is clean and properly scoped.


449-449: Enhanced URI template type with RFC 6570 support

Changing the field type from string to *uritemplate.Template is a solid architectural improvement:

  1. It provides compile-time type safety
  2. It ensures templates are parsed only once (improved performance)
  3. It allows direct access to template expansion methods
  4. The JSON tag remains the same, maintaining backwards compatibility at the protocol level

This change is key to implementing the RFC 6570 support mentioned in the PR objectives.

server/server.go (4)

13-13: Adding appropriate URI template dependency

The addition of the github.com/yosida95/uritemplate/v3 package provides RFC 6570 compliant URI template support, which aligns well with the PR objective.


458-461: Good use of template.URITemplate.Raw() for map indexing

The code correctly uses the raw string representation of the URI template as the map key, which maintains compatibility with lookups while leveraging the structured template object.


659-671: Effective implementation of URI template variable extraction

The updated code properly extracts variables from matched templates and makes them available in request.Params.Arguments. This is a key enhancement that enables dynamic resource URIs with parameters as required by RFC 6570.

The iteration through resource templates, matching logic, and variable extraction is implemented correctly.


697-698: Clean update of matchesTemplate function

The function signature has been properly updated to accept a structured template object instead of a string, and it correctly uses the template's built-in regex matching capabilities.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@ezynda3
Copy link
Contributor

ezynda3 commented Mar 18, 2025

gtg

@ezynda3 ezynda3 merged commit 04c98f0 into mark3labs:main Mar 18, 2025
2 checks passed
@SamMorrowDrums SamMorrowDrums deleted the rfc-6570 branch March 18, 2025 14:31
@SamMorrowDrums
Copy link
Contributor Author

I'm really sorry @ezynda3 but I believe I made the resources/templates/list endpoint return the serialized class rather than a string, so I have fixed it here: #56

Also added a test. I apologise for the inconvenience. Thanks for the fast merge!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Support RFC 6570 for Resource Templates
2 participants