Skip to content

feat: add NewToolResultJSON #550

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

changkun
Copy link

@changkun changkun commented Aug 15, 2025

Description

This PR adds a new util NewToolResultJSON. It is mentioned in https://mcp-go.dev/servers/advanced but the function doesn't really exist.

Type of Change

  • Bug fix (non-breaking change that fixes an issue)
  • New feature (non-breaking change that adds functionality)
  • MCP spec compatibility implementation
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update
  • Code refactoring (no functional changes)
  • Performance improvement
  • Tests only (no functional changes)
  • Other (please describe):

Checklist

  • My code follows the code style of this project
  • I have performed a self-review of my own code
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the documentation accordingly

MCP Spec Compliance

  • This PR implements a feature defined in the MCP specification
  • Link to relevant spec section: Link text
  • Implementation follows the specification exactly

Additional Information

Summary by CodeRabbit

  • New Features

    • Support for JSON-formatted tool results: tools can now return structured JSON alongside text.
    • Improved error reporting when producing tool results to make failure cases clearer to callers.
  • Documentation

    • Updated example code paths and minor formatting fixes in server and HTTP transport guides.

Copy link
Contributor

coderabbitai bot commented Aug 15, 2025

Walkthrough

Adds a new generic helper NewToolResultJSON[T any](data T) in package mcp that marshals the provided data to JSON, returns a CallToolResult with TextContent containing the JSON string and StructuredContent set to the original data, and returns an error on marshal failure. Docs updated to use the new return form.

Changes

Cohort / File(s) Summary of modifications
Tool result helper
mcp/utils.go
Added NewToolResultJSON[T any](data T) (*CallToolResult, error) which marshals data to JSON, sets CallToolResult.Content to a single TextContent with the JSON string, sets CallToolResult.StructuredContent to the original data, and returns a formatted error on marshal failure.
Documentation updates
www/docs/pages/servers/advanced.mdx, www/docs/pages/transports/http.mdx
Updated example call sites to the new NewToolResultJSON return form (call sites changed from return mcp.NewToolResultJSON(...), nil to return mcp.NewToolResultJSON(...)). Minor formatting/noise edits in docs (bullet/spacing adjustments).

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15 minutes

Possibly related PRs

Suggested reviewers

  • fabiante
  • pottekkat

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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: 1

🧹 Nitpick comments (1)
mcp/utils.go (1)

256-258: Tighten doc comment phrasing

Grammar and clarity nit: “a JSON content” is slightly awkward; also explicitly calling out “JSON-encoded text content” improves precision.

-// NewToolResultJSON creates a new CallToolResult with a JSON content.
-// This function panics if the JSON marshalling fails.
+// NewToolResultJSON creates a CallToolResult with JSON-encoded text content,
+// and sets structuredContent to the original value.
📜 Review details

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

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 9f16336 and 9480382.

📒 Files selected for processing (1)
  • mcp/utils.go (1 hunks)
🧰 Additional context used
🧠 Learnings (4)
📓 Common learnings
Learnt from: xinwo
PR: mark3labs/mcp-go#35
File: mcp/tools.go:107-137
Timestamp: 2025-03-04T06:59:43.882Z
Learning: Tool responses from the MCP server shouldn't contain RawInputSchema, which is why the UnmarshalJSON method for the Tool struct is implemented to handle only the structured InputSchema format.
Learnt from: xinwo
PR: mark3labs/mcp-go#35
File: mcp/tools.go:0-0
Timestamp: 2025-03-04T07:00:57.111Z
Learning: The Tool struct in mark3labs/mcp-go handles both InputSchema and RawInputSchema formats. When unmarshaling JSON, it first tries to parse into a structured ToolInputSchema format, and if that fails, it falls back to using the raw schema format, providing symmetry with the MarshalJSON method.
📚 Learning: 2025-03-04T06:59:43.882Z
Learnt from: xinwo
PR: mark3labs/mcp-go#35
File: mcp/tools.go:107-137
Timestamp: 2025-03-04T06:59:43.882Z
Learning: Tool responses from the MCP server shouldn't contain RawInputSchema, which is why the UnmarshalJSON method for the Tool struct is implemented to handle only the structured InputSchema format.

Applied to files:

  • mcp/utils.go
📚 Learning: 2025-03-04T07:00:57.111Z
Learnt from: xinwo
PR: mark3labs/mcp-go#35
File: mcp/tools.go:0-0
Timestamp: 2025-03-04T07:00:57.111Z
Learning: The Tool struct in mark3labs/mcp-go handles both InputSchema and RawInputSchema formats. When unmarshaling JSON, it first tries to parse into a structured ToolInputSchema format, and if that fails, it falls back to using the raw schema format, providing symmetry with the MarshalJSON method.

Applied to files:

  • mcp/utils.go
📚 Learning: 2025-03-04T07:00:57.111Z
Learnt from: xinwo
PR: mark3labs/mcp-go#35
File: mcp/tools.go:0-0
Timestamp: 2025-03-04T07:00:57.111Z
Learning: The Tool struct in the mark3labs/mcp-go project should handle both InputSchema and RawInputSchema consistently between MarshalJSON and UnmarshalJSON methods, even though the tools response from MCP server typically doesn't contain rawInputSchema.

Applied to files:

  • mcp/utils.go
🧬 Code Graph Analysis (1)
mcp/utils.go (3)
mcp/tools.go (1)
  • CallToolResult (40-51)
mcp/types.go (3)
  • Content (885-887)
  • TextContent (891-898)
  • TextContent (900-900)
mcp/consts.go (1)
  • ContentTypeText (4-4)

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)
www/docs/pages/servers/advanced.mdx (2)

133-133: Return updated to use NewToolResultJSON — correct and idiomatic

This matches the new signature that returns (*mcp.CallToolResult, error). Returning the helper directly (without appending ", nil") is the right approach.

For consistency across this page, consider updating earlier examples that hand-roll JSON:

  • Lines 77–83 (in handleCalculateTyped)
  • Lines 288–294 (in the session-aware tool)

to use mcp.NewToolResultJSON(...) as well. It reduces boilerplate and ensures consistent behavior on JSON marshal errors.


133-133: Optional: add a brief note about error propagation

Since NewToolResultJSON can fail on marshal, this example now propagates that error up (good). If you want to show explicit error handling in docs, you could expand this example to demonstrate how to wrap or transform the error in a domain-specific way. Optional.

www/docs/pages/transports/http.mdx (1)

497-497: Return updated to use NewToolResultJSON — correct

This aligns with the helper’s new two-value return and simplifies the example.

Elsewhere in this file, responses are built with fmt.Sprintf JSON strings (e.g., lines 109–111, 140–142, 188–190). Consider switching those to NewToolResultJSON with typed structs or maps to avoid brittle string construction and ensure valid JSON.

📜 Review details

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

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between c31fa3d and f7124ac.

📒 Files selected for processing (3)
  • mcp/utils.go (1 hunks)
  • www/docs/pages/servers/advanced.mdx (2 hunks)
  • www/docs/pages/transports/http.mdx (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • mcp/utils.go
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2025-06-23T11:10:42.948Z
Learnt from: floatingIce91
PR: mark3labs/mcp-go#401
File: server/server.go:1082-1092
Timestamp: 2025-06-23T11:10:42.948Z
Learning: In Go MCP server, ServerTool.Tool field is only used for tool listing and indexing, not for tool execution or middleware. During handleToolCall, only the Handler field is used, so dynamic tools don't need the Tool field populated.

Applied to files:

  • www/docs/pages/servers/advanced.mdx
📚 Learning: 2025-03-04T06:59:43.882Z
Learnt from: xinwo
PR: mark3labs/mcp-go#35
File: mcp/tools.go:107-137
Timestamp: 2025-03-04T06:59:43.882Z
Learning: Tool responses from the MCP server shouldn't contain RawInputSchema, which is why the UnmarshalJSON method for the Tool struct is implemented to handle only the structured InputSchema format.

Applied to files:

  • www/docs/pages/servers/advanced.mdx
🔇 Additional comments (3)
www/docs/pages/servers/advanced.mdx (2)

965-965: Docs formatting change is fine

The “Next Steps” bullet tweak is non-functional and looks good.


133-133: No lingering old NewToolResultJSON(...), nil usages
A repo-wide search located only two call sites—both correctly using the new signature—and no instances of the old , nil pattern remain:

  • www/docs/pages/transports/http.mdx:497
  • www/docs/pages/servers/advanced.mdx:133

All clear.

www/docs/pages/transports/http.mdx (1)

696-696: Docs formatting change is fine

The “Next Steps” bullet formatting update is OK.

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.

1 participant