diff --git a/mcp/utils.go b/mcp/utils.go index b8deeae9c..2d1bd47ba 100644 --- a/mcp/utils.go +++ b/mcp/utils.go @@ -253,6 +253,24 @@ func NewToolResultText(text string) *CallToolResult { } } +// NewToolResultJSON creates a new CallToolResult with a JSON content. +func NewToolResultJSON[T any](data T) (*CallToolResult, error) { + b, err := json.Marshal(data) + if err != nil { + return nil, fmt.Errorf("unable to marshal JSON: %w", err) + } + + return &CallToolResult{ + Content: []Content{ + TextContent{ + Type: ContentTypeText, + Text: string(b), + }, + }, + StructuredContent: data, + }, nil +} + // NewToolResultStructured creates a new CallToolResult with structured content. // It includes both the structured content and a text representation for backward compatibility. func NewToolResultStructured(structured any, fallbackText string) *CallToolResult { diff --git a/www/docs/pages/servers/advanced.mdx b/www/docs/pages/servers/advanced.mdx index 990599b05..7562783df 100644 --- a/www/docs/pages/servers/advanced.mdx +++ b/www/docs/pages/servers/advanced.mdx @@ -130,7 +130,7 @@ func handleCreateUser(ctx context.Context, req mcp.CallToolRequest, input UserCr Status: "created", } - return mcp.NewToolResultJSON(output), nil + return mcp.NewToolResultJSON(output) } ``` @@ -962,4 +962,4 @@ For complete sampling documentation, see **[Server Sampling Guide](/servers/adva ## Next Steps - **[Client Development](/clients)** - Learn to build MCP clients -- **[Server Basics](/servers/basics)** - Review fundamental concepts \ No newline at end of file +- **[Server Basics](/servers/basics)** - Review fundamental concepts diff --git a/www/docs/pages/transports/http.mdx b/www/docs/pages/transports/http.mdx index 9d7e308bc..f41f8350a 100644 --- a/www/docs/pages/transports/http.mdx +++ b/www/docs/pages/transports/http.mdx @@ -494,7 +494,7 @@ func handleStatelessTool(ctx context.Context, req mcp.CallToolRequest) (*mcp.Cal return nil, err } - return mcp.NewToolResultJSON(result), nil + return mcp.NewToolResultJSON(result) } // Use external storage for persistence @@ -693,4 +693,4 @@ The headers are automatically populated by the transport layer and are available - **[In-Process Transport](/transports/inprocess)** - Learn about embedded scenarios - **[Client Development](/clients)** - Build MCP clients for HTTP transport -- **[Server Basics](/servers/basics)** - Review fundamental server concepts \ No newline at end of file +- **[Server Basics](/servers/basics)** - Review fundamental server concepts