Skip to content

feat: support structured content and output schema #460

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 4 commits into from
Jul 28, 2025

Conversation

pottekkat
Copy link
Collaborator

@pottekkat pottekkat commented Jun 28, 2025

Description

Adds support for providing structuredContent in tool result. Also adds an outputSchema automatically from the "structure" of the structuredContent output.

See the examples added in this PR for more info.

Fixes #410

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: Structured Content
  • Implementation follows the specification exactly

Additional Information

This can be treated as an initial draft implementation to try and sense the direction of how this feature must be implemented. Helper functions can be added if this direction is ok for the SDK users OR if this is undesired, it can be scraped and a new one can be implemented.

It is important that we get this right as it is a new non-breaking feature. Once implemented and adopted, it would be difficult to change this.

Summary by CodeRabbit

  • New Features

    • Added support for structured content output in tool results, allowing tools to return both structured data and fallback text.
    • Tools can now declare output schemas, enabling formal specification of structured responses.
    • Introduced new functions and handler types to simplify creation and handling of structured tool results.
    • Provided examples and documentation demonstrating structured output and schema usage.
  • Bug Fixes

    • None.
  • Documentation

    • Added a README example illustrating how to implement and use structured output with output schemas.
  • Tests

    • Added tests to verify output schema generation and structured tool result creation.

Copy link
Contributor

coderabbitai bot commented Jun 28, 2025

Walkthrough

This change introduces structured tool output support by extending the MCP framework. It adds output schema and structured content fields to core types, provides helper functions for structured results, updates tool registration, and includes new examples and tests demonstrating structured output. The update is backward compatible and additive.

Changes

Files/Paths Change Summary
Examples: Structured Output
examples/structured_output/README.md, examples/structured_output/main.go
Added new example and documentation demonstrating structured output and output schema usage.
Module Dependencies
go.mod
Added new dependencies for JSON schema support.
MCP Core: Tools and Schema
mcp/tools.go
Added output schema and structured content fields, new tool options, updated JSON marshaling.
MCP Core: Tests
mcp/tools_test.go
Added tests for output schema and structured result helpers.
MCP Core: Typed Handlers
mcp/typed_tools.go
Added new generic handler type and constructor for structured output handlers.
MCP Core: Utilities
mcp/utils.go
Added helper functions for structured tool results and schema extraction.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes
The changes span multiple core files with new types, methods, and tests, plus new example code. The complexity is moderate due to generic programming, JSON schema integration, and new structured output handling.

Possibly related issues

Possibly related PRs

  • change to strong content type #26: Related to structured output by changing the Content field type in CallToolResult to a strong interface type; complementary but not overlapping.

Suggested labels

type: enhancement, area: sdk

Suggested reviewers

  • ezynda3
  • rwjblue-glean

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 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 decdee8 and 0334dc0.

📒 Files selected for processing (1)
  • mcp/utils.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • mcp/utils.go
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch pottekkat/structured-schema

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.
    • @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 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.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

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

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 (3)
examples/structured_output/README.md (1)

5-5: Fix the bare URL formatting.

The markdown linter flagged this bare URL. Wrap it in angle brackets for better compliance.

-Defined in the MCP spec here: https://modelcontextprotocol.io/specification/2025-06-18/server/tools#structured-content
+Defined in the MCP spec here: <https://modelcontextprotocol.io/specification/2025-06-18/server/tools#structured-content>
mcp/utils.go (1)

482-535: Consider simplifying the schema extraction logic.

The function handles complex $ref resolution but has several potential edge cases that could cause issues. Consider the following improvements:

  1. The $ref parsing assumes a specific format but doesn't validate it
  2. Deep nested references aren't handled
  3. Complex schema structures might not be properly cleaned

Consider adding validation and error handling for edge cases:

// Extract the reference name
refParts := strings.Split(ref, "/")
-if len(refParts) > 0 {
+if len(refParts) > 0 && strings.HasPrefix(ref, "#/$defs/") {
	defName := refParts[len(refParts)-1]
+	if defName == "" {
+		return nil, fmt.Errorf("invalid $ref format: %s", ref)
+	}
	if defSchema, found := defs[defName].(map[string]any); found {

Additionally, consider adding support for other common JSON Schema fields like items, additionalProperties, etc., if they're commonly used in your MCP schemas.

examples/structured_output/main.go (1)

99-112: Consider adding error handling for the manual approach.

While the current implementation works, consider demonstrating error handling in the manual approach to show best practices.

You could enhance the example by showing error handling:

func manualWeatherHandler(ctx context.Context, request mcp.CallToolRequest, args WeatherRequest) (*mcp.CallToolResult, error) {
+	if args.Location == "" {
+		return mcp.NewToolResultError("Location is required"), nil
+	}
+
	response := WeatherResponse{
		Location:    args.Location,
		Temperature: 25.0,
		Units:       "celsius",
		Conditions:  "Sunny, yesterday my life was filled with rain",
		Timestamp:   time.Now(),
	}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1eddde7 and 5ce9da8.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (7)
  • examples/structured_output/README.md (1 hunks)
  • examples/structured_output/main.go (1 hunks)
  • go.mod (1 hunks)
  • mcp/tools.go (6 hunks)
  • mcp/tools_test.go (1 hunks)
  • mcp/typed_tools.go (2 hunks)
  • mcp/utils.go (3 hunks)
🧰 Additional context used
🧠 Learnings (8)
📓 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: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: 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.
examples/structured_output/README.md (5)
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: 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: davidleitw
PR: mark3labs/mcp-go#451
File: mcp/tools.go:1192-1217
Timestamp: 2025-06-26T09:38:18.629Z
Learning: In mcp-go project, the maintainer prefers keeping builder pattern APIs simple without excessive validation for edge cases. The WithOutput* functions are designed to assume correct usage rather than defensive programming, following the principle of API simplicity over comprehensive validation.
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.
go.mod (3)
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: 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.
mcp/typed_tools.go (7)
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: 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 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: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: lariel-fernandes
PR: mark3labs/mcp-go#428
File: www/docs/pages/servers/prompts.mdx:218-234
Timestamp: 2025-06-20T20:39:51.870Z
Learning: In the mcp-go library, the GetPromptParams.Arguments field is of type map[string]string, not map[string]interface{}, so direct string access without type assertions is safe and correct.
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: davidleitw
PR: mark3labs/mcp-go#451
File: mcp/tools.go:1192-1217
Timestamp: 2025-06-26T09:38:18.629Z
Learning: In mcp-go project, the maintainer prefers keeping builder pattern APIs simple without excessive validation for edge cases. The WithOutput* functions are designed to assume correct usage rather than defensive programming, following the principle of API simplicity over comprehensive validation.
mcp/tools_test.go (6)
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 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: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: 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: davidleitw
PR: mark3labs/mcp-go#451
File: mcp/tools.go:1192-1217
Timestamp: 2025-06-26T09:38:18.629Z
Learning: In mcp-go project, the maintainer prefers keeping builder pattern APIs simple without excessive validation for edge cases. The WithOutput* functions are designed to assume correct usage rather than defensive programming, following the principle of API simplicity over comprehensive validation.
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.
mcp/utils.go (6)
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 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: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: davidleitw
PR: mark3labs/mcp-go#451
File: mcp/tools.go:1192-1217
Timestamp: 2025-06-26T09:38:18.629Z
Learning: In mcp-go project, the maintainer prefers keeping builder pattern APIs simple without excessive validation for edge cases. The WithOutput* functions are designed to assume correct usage rather than defensive programming, following the principle of API simplicity over comprehensive validation.
examples/structured_output/main.go (6)
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: davidleitw
PR: mark3labs/mcp-go#451
File: mcp/tools.go:1192-1217
Timestamp: 2025-06-26T09:38:18.629Z
Learning: In mcp-go project, the maintainer prefers keeping builder pattern APIs simple without excessive validation for edge cases. The WithOutput* functions are designed to assume correct usage rather than defensive programming, following the principle of API simplicity over comprehensive validation.
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.
mcp/tools.go (5)
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: 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: davidleitw
PR: mark3labs/mcp-go#451
File: mcp/tools.go:1192-1217
Timestamp: 2025-06-26T09:38:18.629Z
Learning: In mcp-go project, the maintainer prefers keeping builder pattern APIs simple without excessive validation for edge cases. The WithOutput* functions are designed to assume correct usage rather than defensive programming, following the principle of API simplicity over comprehensive validation.
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.
🧬 Code Graph Analysis (4)
mcp/typed_tools.go (2)
mcp/tools.go (2)
  • CallToolRequest (52-55)
  • CallToolResult (38-49)
mcp/utils.go (2)
  • NewToolResultError (345-355)
  • NewToolResultStructuredOnly (274-288)
mcp/tools_test.go (3)
mcp/tools.go (5)
  • NewTool (582-604)
  • WithDescription (625-629)
  • WithOutputSchema (633-651)
  • WithString (893-911)
  • Required (725-729)
mcp/utils.go (1)
  • NewToolResultStructured (260-270)
mcp/types.go (3)
  • Content (827-829)
  • TextContent (833-838)
  • TextContent (840-840)
mcp/utils.go (2)
mcp/tools.go (1)
  • CallToolResult (38-49)
mcp/types.go (3)
  • Content (827-829)
  • TextContent (833-838)
  • TextContent (840-840)
mcp/tools.go (1)
mcp/utils.go (1)
  • ExtractMCPSchema (483-535)
🪛 markdownlint-cli2 (0.17.2)
examples/structured_output/README.md

5-5: Bare URL used
null

(MD034, no-bare-urls)

🔇 Additional comments (18)
go.mod (2)

7-7: LGTM! Dependency addition supports structured output feature.

The addition of github.com/invopop/jsonschema aligns perfectly with the PR objective to support automatic output schema generation for structured content.


14-19: Indirect dependencies look appropriate.

The new indirect dependencies (bahlo/generic-list-go, buger/jsonparser, mailru/easyjson, wk8/go-ordered-map/v2) are expected transitive dependencies of the jsonschema library and support JSON processing utilities.

examples/structured_output/README.md (1)

11-44: Excellent documentation with clear examples.

The code examples clearly demonstrate the new structured output functionality:

  • Struct definition with JSON schema tags
  • Tool creation with output schema
  • Handler implementation returning structured data

This provides great guidance for SDK users implementing the new feature.

mcp/typed_tools.go (2)

11-12: Well-designed generic handler function type.

The StructuredToolHandlerFunc provides excellent type safety by parameterizing both input arguments and output result types, enabling strongly-typed structured output handling.


25-42: Robust implementation with proper error handling.

The NewStructuredToolHandler function correctly:

  • Binds arguments with error handling
  • Executes the handler with error propagation
  • Creates structured-only results for backward compatibility
  • Follows the established pattern from NewTypedToolHandler

The use of NewToolResultStructuredOnly ensures both structured content and fallback text are provided as required by the MCP specification.

mcp/tools_test.go (2)

532-562: Comprehensive test for output schema generation.

The test effectively validates:

  • Schema generation from Go structs with JSON schema tags
  • Proper setting of RawOutputSchema field
  • JSON marshaling includes outputSchema field
  • Integration with the tool builder pattern

The test struct with various JSON schema tags provides good coverage of the schema generation functionality.


564-581: Good test coverage for structured tool results.

The test properly verifies that NewToolResultStructured creates results with:

  • Correct fallback text content
  • Non-nil structured content field
  • Proper content array structure

This ensures the structured output feature works as expected for both structured and fallback content.

mcp/tools.go (6)

10-10: Appropriate dependency addition for schema generation.

The github.com/invopop/jsonschema import enables automatic JSON schema generation from Go types, which is essential for the new output schema functionality.


41-44: Well-documented structured content field.

The StructuredContent field addition properly follows the MCP specification for structured content support. The documentation clearly explains the backward compatibility requirement to provide functionally equivalent unstructured content.


487-488: Correct implementation of output schema field.

The RawOutputSchema field is properly:

  • Hidden from JSON marshaling with json:"-" tag
  • Well-documented as optional
  • Positioned logically after input schema fields

This follows the same pattern as RawInputSchema and maintains consistency.


502-502: Proper map sizing and output schema handling.

The map capacity increase to 5 accounts for the new output schema field. The output schema is correctly added to the JSON only when present, maintaining backward compatibility.

Also applies to: 521-524


631-651: Excellent generic output schema function.

The WithOutputSchema[T any]() function provides an elegant API for automatic schema generation:

  • Uses reflection to generate schema from Go types
  • Extracts MCP-compatible schema via ExtractMCPSchema
  • Silently ignores errors for backward compatibility
  • Follows the maintainer's preference for simple APIs without excessive validation

The approach aligns with the retrieved learning about keeping builder pattern APIs simple.


653-662: Good raw schema option for advanced use cases.

The WithRawOutputSchema function provides necessary flexibility for complex schemas that can't be auto-generated from Go types, complementing the generic WithOutputSchema function nicely.

mcp/utils.go (2)

6-6: LGTM - Necessary imports for new functionality.

The additional imports support the new structured content features: strings for string manipulation in schema processing and jsonschema for schema generation.

Also applies to: 8-8


258-270: LGTM - Clean helper function for structured results.

This function provides a clear API for creating structured tool results with explicit fallback text, which aligns well with the MCP specification's recommendation for backward compatibility.

examples/structured_output/main.go (3)

12-17: Good use of schema description tags.

The jsonschema_description tags will help generate meaningful API documentation for the tools. This is a good pattern for developers to follow.


38-73: Excellent demonstration of structured output patterns.

The example effectively showcases three different approaches:

  1. Auto-generated schema with structured handler
  2. Nested struct schema
  3. Manual result creation

This provides developers with multiple implementation options based on their needs.


75-88: Clean handler implementation with temperature conversion.

The handler properly processes the input arguments and includes business logic (temperature unit conversion). Good example of a realistic tool implementation.

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)
examples/structured_output/main.go (1)

94-137: Handler implementations are well-structured with one typo to fix.

The handler functions properly demonstrate structured output patterns with appropriate validation and bounds checking. However, there's a typo in the asset data.

Fix the asset name typo:

-		{ID: "dot", Name: "Pottedot", Value: 18.45, Currency: "USD"},
+		{ID: "dot", Name: "Polkadot", Value: 18.45, Currency: "USD"},
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5ce9da8 and 085c67d.

📒 Files selected for processing (3)
  • examples/structured_output/main.go (1 hunks)
  • mcp/tools.go (6 hunks)
  • mcp/utils.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • mcp/utils.go
  • mcp/tools.go
🧰 Additional context used
🧠 Learnings (2)
📓 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: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: 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.
examples/structured_output/main.go (6)
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: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: davidleitw
PR: mark3labs/mcp-go#451
File: mcp/tools.go:1192-1217
Timestamp: 2025-06-26T09:38:18.629Z
Learning: In mcp-go project, the maintainer prefers keeping builder pattern APIs simple without excessive validation for edge cases. The WithOutput* functions are designed to assume correct usage rather than defensive programming, following the principle of API simplicity over comprehensive validation.
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: 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.
🔇 Additional comments (3)
examples/structured_output/main.go (3)

1-47: Well-structured type definitions for schema generation.

The import statements and struct definitions properly demonstrate the new structured output features. The jsonschema_description tags will enable automatic schema generation as intended by this PR.


49-92: Excellent demonstration of structured output capabilities.

The main function effectively showcases all the new structured output features introduced in this PR:

  • Auto-generated output schemas with WithOutputSchema[T]()
  • Different handler types (NewStructuredToolHandler, NewTypedToolHandler)
  • Various output types (structs, arrays, manual creation)

This provides a comprehensive example for SDK users.


139-152: Excellent demonstration of manual structured result creation.

This handler effectively showcases the NewToolResultStructured utility function, demonstrating how to create structured output with fallback text. This pattern provides SDK users with fine-grained control over tool results while maintaining backward compatibility.


return &CallToolResult{
Content: []Content{
TextContent{
Copy link
Contributor

Choose a reason for hiding this comment

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

This still returns fallback text so naming doesn't really match with behavior...

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I will update the documentation to be more clear. As per the spec, there should always be a fallback.

mcpSchema, err := json.Marshal(schema)
if err != nil {
// Skip and maintain backward compatibility
return
Copy link
Contributor

Choose a reason for hiding this comment

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

should we log this?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Maybe we can add a tool validation logic later?

@David-Kreiner
Copy link

Can we converge on one of these PRs? Would love to see this feature in the SDK. @ezynda3 @pottekkat

this one or #451?

@pottekkat
Copy link
Collaborator Author

@David-Kreiner, others, sorry for the delay in getting this merged. It will be merged and released today.

@ezynda3 ezynda3 merged commit 8f9d538 into main Jul 28, 2025
4 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.

Task: Add Structured Tool Output Support
4 participants