Skip to content

fix CallToolResult json marshaling and unmarshaling: need structuredC… #523

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

Merged
merged 8 commits into from
Aug 11, 2025

Conversation

sunfuze
Copy link
Contributor

@sunfuze sunfuze commented Jul 31, 2025

CallToolRequest lost the value of StructuredContent when do json marshal and unmarshal

Description

CallToolRequest defines the MarshalerJSON and UnmarshalJSON methods, which are used by json.Marshal and json.Unmarshal. When structuredContent exists, it needs to be added to the target return.

Fixes #522

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

Summary by CodeRabbit

  • New Features

    • Tool results can include structured content alongside text for richer responses.
  • Bug Fixes

    • Improved JSON handling and parsing of structured content so it displays correctly and reliably.
  • Tests

    • Added comprehensive tests for marshaling/unmarshaling, round-trip integrity, and edge cases for structured content.
    • Added an integration-style test verifying a tool response containing both text and structured content.

Copy link
Contributor

coderabbitai bot commented Jul 31, 2025

Walkthrough

Updated CallToolResult JSON marshal/unmarshal and parsing to include the StructuredContent field; added unit tests for marshaling, unmarshaling, round-trip and edge cases; and added a server test validating tool responses with structured content.

Changes

Cohort / File(s) Change Summary
CallToolResult JSON marshal/unmarshal logic
mcp/tools.go
Extended MarshalJSON() and UnmarshalJSON() of CallToolResult to include handling for the StructuredContent field.
CallToolResult tests
mcp/tools_test.go
Added tests: TestCallToolResultMarshalJSON, TestCallToolResultUnmarshalJSON, TestCallToolResultRoundTrip, TestCallToolResultEdgeCases to exercise structured content scenarios.
Parsing logic update
mcp/utils.go
Updated ParseCallToolResult to detect and assign structuredContent from parsed JSON into CallToolResult.StructuredContent.
Server tool structured content test
mcptest/mcptest_test.go
Added TestServerWithToolStructuredContent and structuredContentHandler to validate a tool returning both text and structured content.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15 minutes

Assessment against linked issues

Objective Addressed Explanation
Parse and assign StructuredContent in ParseCallToolResult (#522)
Include StructuredContent when marshaling CallToolResult (#522)
Add tests verifying marshal/unmarshal including StructuredContent (#522)

Possibly related PRs

Suggested labels

area: sdk

Suggested reviewers

  • pottekkat

📜 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 6bdac1e and d821d49.

📒 Files selected for processing (1)
  • mcptest/mcptest_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • mcptest/mcptest_test.go
✨ 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.
    • Explain this complex logic.
    • 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 explain this code block.
  • 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 explain its main purpose.
    • @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 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 generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests 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.

@pottekkat
Copy link
Collaborator

@sunfuze thanks. Can you check the CI tests?

@jeremyatvideoamp
Copy link

I'm looking forward to using this when it's ready.

@lixingbu-tal
Copy link

I'm looking forward to using this when it's ready.

I'm looking forward to it too

@sunfuze
Copy link
Contributor Author

sunfuze commented Aug 7, 2025

@sunfuze thanks. Can you check the CI tests?

Done. When marshal to json string, the int type will change to float for json use float to store number type.

@aronkof
Copy link

aronkof commented Aug 7, 2025

anything else we could help to push this forward?
also, is there any workaround for this without this fix? or should I move on with a fork until then?

maybe add structured response implementations to the root mcptest package tests, what do you think about this @sunfuze ?

@ivanovpetr
Copy link

I am looking forward to it if you want to know😉

@pottekkat
Copy link
Collaborator

@sunfuze There seems to be issues still. You can run these tests locally before you push.

@pottekkat
Copy link
Collaborator

I'm sorry for the delay. We should have implemented this the first time when we added support for it on the server side. But I overlooked it and I was also using the SDK mostly for MCP servers. Once the tests are fixed, we will merge it and make a new release.

@sunfuze
Copy link
Contributor Author

sunfuze commented Aug 8, 2025

anything else we could help to push this forward? also, is there any workaround for this without this fix? or should I move on with a fork until then?

Only need pull latest main branch, repository is quite active, and the modified branch has not been merged.

maybe add structured response implementations to the root mcptest package tests, what do you think about this @sunfuze ?

Yes, we can add a case to test tool handler response structured content.

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 (1)
mcptest/mcptest_test.go (1)

191-275: Good end-to-end coverage for structured content; add error-state assertion and negative-path test

  • Add a quick assertion that the tool result is not an error.
  • Consider a companion test for the missing user_id case to validate NewToolResultError path.

Suggested inline tweak:

@@
   result, err := client.CallTool(ctx, req)
   if err != nil {
     t.Fatal("CallTool:", err)
   }
 
+  if result.IsError {
+    t.Fatalf("unexpected error result: %+v", result)
+  }
+
   if len(result.Content) != 1 {
     t.Fatalf("Expected 1 content item, got %d", len(result.Content))
   }

Optional additional test outside this block:

func TestServerWithToolStructuredContent_MissingUserID(t *testing.T) {
  ctx := context.Background()
  srv, err := mcptest.NewServer(t, server.ServerTool{
    Tool: mcp.NewTool("get_user",
      mcp.WithDescription("Gets user information with structured data."),
      mcp.WithString("user_id", mcp.Description("The user ID to look up.")),
    ),
    Handler: structuredContentHandler,
  })
  if err != nil {
    t.Fatal(err)
  }
  defer srv.Close()

  client := srv.Client()

  var req mcp.CallToolRequest
  req.Params.Name = "get_user"
  // no user_id argument

  result, err := client.CallTool(ctx, req)
  if err != nil {
    t.Fatal("CallTool:", err)
  }
  if !result.IsError {
    t.Fatalf("expected error result when user_id is missing, got: %+v", result)
  }
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0ba984a and 36d32f9.

📒 Files selected for processing (2)
  • mcp/utils.go (1 hunks)
  • mcptest/mcptest_test.go (1 hunks)
🧰 Additional context used
🧠 Learnings (7)
📓 Common learnings
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.
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.
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.
Learnt from: octo
PR: mark3labs/mcp-go#149
File: mcptest/mcptest.go:0-0
Timestamp: 2025-04-21T21:26:32.945Z
Learning: In the mcptest package, prefer returning errors from helper functions rather than calling t.Fatalf() directly, giving callers flexibility in how to handle errors.
Learnt from: ezynda3
PR: mark3labs/mcp-go#461
File: server/sampling.go:22-26
Timestamp: 2025-06-30T07:13:17.052Z
Learning: In the mark3labs/mcp-go project, the MCPServer.capabilities field is a struct value (serverCapabilities), not a pointer, so it cannot be nil and doesn't require nil checking. Only pointer fields within the capabilities struct should be checked for nil.
📚 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
  • mcptest/mcptest_test.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
  • mcptest/mcptest_test.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
  • mcptest/mcptest_test.go
📚 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:

  • mcp/utils.go
  • mcptest/mcptest_test.go
📚 Learning: 2025-06-30T07:13:17.052Z
Learnt from: ezynda3
PR: mark3labs/mcp-go#461
File: server/sampling.go:22-26
Timestamp: 2025-06-30T07:13:17.052Z
Learning: In the mark3labs/mcp-go project, the MCPServer.capabilities field is a struct value (serverCapabilities), not a pointer, so it cannot be nil and doesn't require nil checking. Only pointer fields within the capabilities struct should be checked for nil.

Applied to files:

  • mcp/utils.go
  • mcptest/mcptest_test.go
📚 Learning: 2025-04-21T21:26:32.945Z
Learnt from: octo
PR: mark3labs/mcp-go#149
File: mcptest/mcptest.go:0-0
Timestamp: 2025-04-21T21:26:32.945Z
Learning: In the mcptest package, prefer returning errors from helper functions rather than calling t.Fatalf() directly, giving callers flexibility in how to handle errors.

Applied to files:

  • mcptest/mcptest_test.go
🔇 Additional comments (2)
mcp/utils.go (2)

673-678: StructuredContent parsing added — LGTM

This fixes the loss of structuredContent during parsing. Placement and behavior are correct, and it’s non-breaking.


673-678: structuredContent key is consistent across struct tags, custom JSON methods, and tests

No inconsistencies found—json:"structuredContent" in CallToolResult, its MarshalJSON/UnmarshalJSON implementations, and all related tests use the same key. No changes required.

@ezynda3 ezynda3 merged commit 9c5d303 into mark3labs:main Aug 11, 2025
4 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Aug 15, 2025
16 tasks
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.

bug: StructuredContent not parsed in utils.ParseCallToolResult
7 participants