Skip to content

Conversation

@xinwo
Copy link
Contributor

@xinwo xinwo commented Mar 3, 2025

similiar to #26, add strong type to ResourceContents

Summary by CodeRabbit

  • New Features

    • Introduced a unified mechanism for processing resource responses, enabling consistent handling of different resource content types.
  • Refactor

    • Improved resource parsing and error management for more reliable and clearly structured resource details.
    • Enhanced type specificity across resource operations to ensure consistent and stable outputs for consumers.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 3, 2025

Walkthrough

This pull request refactors the resource reading and parsing logic across multiple components. The changes replace explicit JSON unmarshalling in client methods with dedicated parsing functions, and update return types from generic []interface{} to a strongly typed []mcp.ResourceContents. Additionally, the types in the MCP package are modified to enforce type safety via an interface-based design with new parsing helpers added in the utilities. Overall, the changes standardize and simplify resource handling.

Changes

File(s) Change Summary
client/sse.go, client/stdio.go Updated ReadResource methods to replace JSON unmarshalling with a direct call to mcp.ParseReadResourceResult, removing explicit error handling for unmarshalling.
examples/everything/main.go Modified handleReadResource and handleResourceTemplate to return []mcp.ResourceContents (using TextResourceContents) instead of []interface{}, simplifying the return structure.
mcp/types.go Changed ReadResourceResult.Contents from []interface{} to []ResourceContents and redefined ResourceContents as an interface with implementations provided by TextResourceContents and BlobResourceContents.
mcp/utils.go Introduced new helper functions: ParseResourceContents to centralize resource field extraction and ParseReadResourceResult to process JSON messages, enhancing type safety and error handling.
server/server.go, server/server_test.go Updated resource handler function signatures to return []mcp.ResourceContents instead of []interface{}, and simplified the return structure to directly use TextResourceContents.

Sequence Diagram(s)

sequenceDiagram
    participant Client as Client Method
    participant Parser as mcp.ParseReadResourceResult
    participant Utils as mcp.ParseResourceContents

    Client->>Parser: Pass JSON response
    Parser->>Utils: Parse each resource field
    Utils-->>Parser: Return ResourceContent instance
    Parser-->>Client: Return structured ReadResourceResult
Loading

Possibly related PRs

  • change to strong content type #26: Involves similar refactoring by removing JSON unmarshalling logic and introducing parsing functions in the ReadResource implementations.

Suggested reviewers

  • ezynda3

Poem

I'm a little rabbit, hopping through code with delight,
Skipping over JSON clutter to bring clarity to light.
I nibble on errors, whoopsy-daisy corrected,
With parse functions fresh and nicely erected.
🐰 Hop along, dear devs, for our code feels so right!
Happy trails in our refactor flight!

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (3)
examples/everything/main.go (1)

189-194: Validate dynamic resource parameters

While the typed return is consistent, consider checking if request.Params.URI is empty or malformed before returning the resource to handle potential user input issues gracefully.

mcp/utils.go (2)

537-562: Extendable parsing for new resource types

Current checks for text or blob are appropriate, but consider anticipating future extensions (e.g., JSON resource contents) or additional metadata fields if requirements evolve.


564-606: Robust parsing of read resource results

This end-to-end solution properly checks for array presence and object structure. For advanced debugging, you might log partial parsing failures or invalid entries before returning an error.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5dab240 and 5b6fa01.

📒 Files selected for processing (7)
  • client/sse.go (1 hunks)
  • client/stdio.go (1 hunks)
  • examples/everything/main.go (1 hunks)
  • mcp/types.go (2 hunks)
  • mcp/utils.go (3 hunks)
  • server/server.go (1 hunks)
  • server/server_test.go (1 hunks)
🔇 Additional comments (12)
mcp/types.go (4)

376-376: Strong typing improved, replacing interface{} with ResourceContents

Changing the Contents field from []interface{} to []ResourceContents significantly improves type safety and code clarity. This change enforces that only proper resource content types can be included in the results.


462-464: Well-designed interface approach for type safety

Converting ResourceContents from a concrete struct to an interface with a marker method is an excellent design choice. This pattern (sometimes called the "marker interface pattern") prevents arbitrary types from being used as ResourceContents while enabling polymorphism. Only types that explicitly implement isResourceContents() can be used in this context.


476-476: Implementation satisfies interface contract

This marker method implementation correctly satisfies the ResourceContents interface contract, enabling TextResourceContents to be used where ResourceContents is expected.


487-487: Implementation satisfies interface contract

This marker method implementation correctly satisfies the ResourceContents interface contract, enabling BlobResourceContents to be used where ResourceContents is expected.

client/stdio.go (1)

341-341: Improved encapsulation with centralized parsing

Replacing direct JSON unmarshaling with a call to mcp.ParseReadResourceResult(response) is a good refactoring that:

  1. Centralizes parsing logic, making it consistent across the codebase
  2. Reduces code duplication
  3. Makes the code more maintainable as parsing logic is in a single place
  4. Aligns with the new strongly-typed ResourceContents interface

This change is consistent with similar changes in other client implementations.

client/sse.go (1)

415-415: Improved encapsulation with centralized parsing

Replacing direct JSON unmarshaling with a call to mcp.ParseReadResourceResult(response) maintains consistency with other client implementations and centralizes the parsing logic. This makes the code more maintainable and ensures uniform handling of the new strongly-typed ResourceContents interface.

server/server_test.go (2)

677-679: Function signature correctly updated to use strongly-typed return

The function signature has been properly updated to return []mcp.ResourceContents instead of []interface{}, which aligns with the type system improvements made elsewhere. This makes the test implementation type-safe and consistent with the production code.


680-683: Simplified return structure without unnecessary nesting

The return structure has been simplified by directly using TextResourceContents as an implementation of the ResourceContents interface, rather than wrapping it in another struct. This makes the code cleaner and more direct while satisfying the interface requirements.

server/server.go (1)

32-35: Promoting stronger typing for resource handlers

Switching from []interface{} to []mcp.ResourceContents significantly improves type safety and clarity, eliminating the overhead of downcasting and reducing runtime errors.

examples/everything/main.go (1)

176-181: Typed resource return enhances clarity

Returning a slice of mcp.ResourceContents ensures a well-defined structure for the resource, aiding maintainability and self-documentation of handler behavior.

mcp/utils.go (2)

308-313: Typed contents improve predictability

Using []ResourceContents in NewReadResourceResult aligns with the strongly-typed approach, reducing ambiguity and potential misuse compared to []interface{}.


413-419: Consolidated resource parsing

Forwarding embedded resource maps to ParseResourceContents keeps the code organized, centralizes error handling, and streamlines content validation logic.

@ezynda3 ezynda3 self-assigned this Mar 3, 2025
@ezynda3 ezynda3 merged commit 5c2faf4 into mark3labs:main Mar 3, 2025
2 checks passed
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.

2 participants