Skip to content

mcp: client panics when a server sends a null message in sampling/createMessage #1563

Done

Description

@rene-founder

Checklist

  • I searched the existing issues, and this has not been reported before.
  • This is a real problem that I ran into myself, using the latest release of the SDK.
  • I ran into it in a production system, not in a toy example, a benchmark, or an automated or AI-driven scan of the code.
  • I (a human) examined the relevant SDK code, and wrote or reviewed every line of this report. It is not unreviewed AI output.
  • This report is brief and concise, and sticks to the facts needed to understand the problem.

What happened?

If a client sets ClientOptions.CreateMessageHandler, a server can crash the client process by sending a sampling request whose messages contain null:

{"jsonrpc":"2.0","id":77,"method":"sampling/createMessage","params":{"maxTokens":1,"messages":[null]}}

CreateMessageWithToolsParams.Messages is []*SamplingMessageV2, so the null decodes to a nil pointer. (*Client).createMessage (mcp/client.go:756 on main) calls toBase() before calling the handler, and toBase() reads len(m.Content) without checking m (mcp/protocol.go:835). The panic happens on a goroutine started by the SDK, so the process exits and the handler is never called.

I see the same thing when the message comes from the inputRequests of a tool result (program below), on both protocol 2025-11-25 and 2026-07-28. It happens on v1.9.0 (client.go:732) and on main at 723d70e. A client that sets CreateMessageWithToolsHandler instead does not panic; its handler gets the nil element.

Run with v1.9.0 or main, the program below prints protocol 2026-07-28, then panics and exits with status 2; "handler called" is never printed.

A message with "content":null is already rejected while decoding, with -32602; a null message gets past decoding because the slice holds pointers.

Expected: the client answers with -32602 (Invalid params) and keeps running.

Possible fix: in toBase(), return fmt.Errorf("%w: null message in sampling request", jsonrpc2.ErrInvalidParams) for a nil message, the same wrapping used for params that fail to decode. createMessage is its only caller, and CreateMessageWithToolsHandler keeps getting the request as it does today. If you'd rather reject the null message during decoding, which would cover that handler too, I can do that instead.

For the test, I'd add TestCreateMessage_NilMessage to sampling_test.go, next to TestCreateMessage_MultipleContentError. It checks the error code and goes through a tool's inputRequests on both protocol versions, the same way TestMultiRoundTrip_NilHandlerResult does. It panics without the fix and passes with it. With the fix, go test ./..., go test -race ./mcp/... and go vet ./... pass on main.

I have a minimal candidate patch and regression test available if the maintainers would find them useful.

AI disclosure: I used AI tools to find this, reproduce it and draft this report. I checked the code, the reproduction and the text myself, and I'm responsible for it.

How to reproduce

package main

import (
	"context"
	"fmt"

	"github.com/modelcontextprotocol/go-sdk/mcp"
)

func main() {
	ctx := context.Background()
	impl := &mcp.Implementation{Name: "repro", Version: "v1"}

	server := mcp.NewServer(impl, nil)
	server.AddTool(&mcp.Tool{Name: "t", InputSchema: map[string]any{"type": "object"}},
		func(context.Context, *mcp.CallToolRequest) (*mcp.CallToolResult, error) {
			// Sent on the wire as "messages":[null].
			return &mcp.CallToolResult{InputRequests: mcp.InputRequestMap{
				"s": &mcp.CreateMessageWithToolsParams{MaxTokens: 1, Messages: []*mcp.SamplingMessageV2{nil}},
			}}, nil
		})
	ct, st := mcp.NewInMemoryTransports()
	if _, err := server.Connect(ctx, st, nil); err != nil {
		panic(err)
	}

	client := mcp.NewClient(impl, &mcp.ClientOptions{
		CreateMessageHandler: func(context.Context, *mcp.CreateMessageRequest) (*mcp.CreateMessageResult, error) {
			fmt.Println("handler called")
			return &mcp.CreateMessageResult{Model: "m", Role: "assistant", Content: &mcp.TextContent{Text: "ok"}}, nil
		},
	})
	cs, err := client.Connect(ctx, ct, nil)
	if err != nil {
		panic(err)
	}
	defer cs.Close()

	fmt.Println("protocol", cs.InitializeResult().ProtocolVersion)
	_, err = cs.CallTool(ctx, &mcp.CallToolParams{Name: "t"})
	fmt.Println("CallTool returned:", err)
}

Where did you hit this?

Not in production; found while reviewing the sampling code with AI tools, then reproduced with the program above.

Go MCP SDK version

v1.9.0, and main at 723d70e

Go version

go version go1.27.4 linux/amd64

Logs

anic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0xcc749e]

goroutine 14 [running]:
github.com/modelcontextprotocol/go-sdk/mcp.(*CreateMessageWithToolsParams).toBase(0xc0001eb4a0)
	mcp/protocol.go:835 +0xde
github.com/modelcontextprotocol/go-sdk/mcp.(*Client).createMessage(0xc0000e2180, {0x198a720, 0xc0002364e0}, 0xc00009b760)
	mcp/client.go:756 +0x25c

Activity

  1. added a commit that references this issue on Dec 2, 2026
    2673d55
  2. rene-founder commented on Dec 2, 2026

    @rene-founder
    ContributorAuthor

    I'd like to fix this myself and send a PR, if that works for you.

    While preparing the fix, I found a second nil-handling path: createMessageParamsToWithTools in mcp/mrtr.go reads each message without a nil check. In a 2025-11-25 session, when a tool returns an InputRequests entry of type *CreateMessageParams with a nil message, this panics the server in the multi-round-trip shim at mrtr.go:225, before anything is sent to the client.

    My candidate handles both paths:

    • toBase() returns fmt.Errorf("%w: null message in sampling request", jsonrpc2.ErrInvalidParams) for a nil message.
    • createMessageParamsToWithTools preserves a nil element so it reaches the client and is rejected with -32602, rather than panicking the server.
    • TestCreateMessage_NilMessage checks the error code and exercises a tool's InputRequests with both CreateMessageWithToolsParams and CreateMessageParams, on protocol versions 2026-07-28 and 2025-11-25. The test passes with both fixes; reverting either fix reproduces the corresponding client or server panic.

    On the candidate based on main at 723d70e, go test -race ./mcp/..., go vet ./..., and gofmt -l mcp/ completed cleanly.

    AI tools helped me find the second path, write the patch, and run the tests. I reviewed the change and the test output, and I take responsibility for it.

  3. guglielmo-san commented on Dec 4, 2026

    @guglielmo-san
    Contributor

    @rene-founder i assigned the issue to you, you can open a PR now!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions