package mcp

import (
	
	
)

// Multi round-trip requests (MRTR), introduced in protocol version 2026-07-28
// (SEP-2322), replace server-initiated elicitation/create,
// sampling/createMessage, and roots/list requests.
//
// Instead of pushing a request down a held-open stream, a server returns an
// [InputRequiredResult]: a result whose resultType is
// [ResultTypeInputRequired] and which carries the requests it needs answered.
// The client fulfils them and retries the original request with the answers in
// inputResponses, echoing the opaque requestState back verbatim.

// InputRequest is a single server-initiated request embedded in an
// [InputRequiredResult]. Exactly one of its fields is populated, selected by
// the Method field.
type InputRequest struct {
	// Method is the JSON-RPC method of the embedded request: one of
	// [MethodElicitationCreate], [MethodSamplingCreateMessage], or
	// [MethodListRoots].
	Method MCPMethod `json:"method"`

	// Elicitation is set when Method is elicitation/create.
	Elicitation *ElicitationParams `json:"-"`
	// Sampling is set when Method is sampling/createMessage.
	Sampling *CreateMessageParams `json:"-"`
	// Roots is set when Method is roots/list. The roots/list request takes no
	// parameters, so this is an empty struct used only as a presence marker.
	Roots *ListRootsParams `json:"-"`
}

// ListRootsParams are the (empty) parameters of a roots/list request. It
// exists so that [InputRequest] can represent a roots/list request uniformly.
type ListRootsParams struct{}

// NewElicitationInputRequest builds an input request asking the client to
// elicit information from the user.
func ( ElicitationParams) InputRequest {
	return InputRequest{Method: MethodElicitationCreate, Elicitation: &}
}

// NewSamplingInputRequest builds an input request asking the client to sample
// from an LLM.
func ( CreateMessageParams) InputRequest {
	return InputRequest{Method: MethodSamplingCreateMessage, Sampling: &}
}

// NewRootsInputRequest builds an input request asking the client for its list
// of roots.
func () InputRequest {
	return InputRequest{Method: MethodListRoots, Roots: &ListRootsParams{}}
}

// MarshalJSON encodes the input request as a JSON-RPC request object carrying
// the method and its parameters.
func ( InputRequest) () ([]byte, error) {
	 := map[string]any{"method": .Method}
	switch .Method {
	case MethodElicitationCreate:
		if .Elicitation == nil {
			return nil, fmt.Errorf("input request %s: missing elicitation params", .Method)
		}
		["params"] = .Elicitation
	case MethodSamplingCreateMessage:
		if .Sampling == nil {
			return nil, fmt.Errorf("input request %s: missing sampling params", .Method)
		}
		["params"] = .Sampling
	case MethodListRoots:
		// roots/list takes no parameters.
	default:
		return nil, fmt.Errorf("unsupported input request method %q", .Method)
	}
	return json.Marshal()
}

// UnmarshalJSON decodes a JSON-RPC request object into the matching variant.
func ( *InputRequest) ( []byte) error {
	var  struct {
		 MCPMethod       `json:"method"`
		 json.RawMessage `json:"params"`
	}
	if  := json.Unmarshal(, &);  != nil {
		return 
	}
	* = InputRequest{Method: .}
	switch . {
	case MethodElicitationCreate:
		var  ElicitationParams
		if len(.) > 0 {
			if  := json.Unmarshal(., &);  != nil {
				return fmt.Errorf("input request %s: %w", ., )
			}
		}
		.Elicitation = &
	case MethodSamplingCreateMessage:
		var  CreateMessageParams
		if len(.) > 0 {
			if  := json.Unmarshal(., &);  != nil {
				return fmt.Errorf("input request %s: %w", ., )
			}
		}
		.Sampling = &
	case MethodListRoots:
		.Roots = &ListRootsParams{}
	default:
		return fmt.Errorf("unsupported input request method %q", .)
	}
	return nil
}

// InputResponse is a client's answer to a single [InputRequest]. Exactly one
// of its fields is populated, matching the method of the request it answers.
type InputResponse struct {
	// Elicitation answers an elicitation/create input request.
	Elicitation *ElicitationResult `json:"-"`
	// Sampling answers a sampling/createMessage input request.
	Sampling *CreateMessageResult `json:"-"`
	// Roots answers a roots/list input request.
	Roots *ListRootsResult `json:"-"`

	// raw preserves the original JSON so that a response can be round-tripped
	// and decoded against the method of the request it answers.
	raw json.RawMessage
}

// NewElicitationInputResponse builds an input response carrying an elicitation
// result.
func ( ElicitationResult) InputResponse {
	return InputResponse{Elicitation: &}
}

// NewSamplingInputResponse builds an input response carrying a sampling
// result.
func ( CreateMessageResult) InputResponse {
	return InputResponse{Sampling: &}
}

// NewRootsInputResponse builds an input response carrying a roots list.
func ( ListRootsResult) InputResponse {
	return InputResponse{Roots: &}
}

// MarshalJSON encodes whichever variant is populated.
func ( InputResponse) () ([]byte, error) {
	switch {
	case .Elicitation != nil:
		return json.Marshal(.Elicitation)
	case .Sampling != nil:
		return json.Marshal(.Sampling)
	case .Roots != nil:
		return json.Marshal(.Roots)
	case len(.raw) > 0:
		return .raw, nil
	default:
		return []byte("null"), nil
	}
}

// UnmarshalJSON stores the raw payload. Input responses are a union whose
// variant is determined by the method of the corresponding [InputRequest],
// which is not present in the response itself, so decoding into a concrete
// type is deferred to [InputResponse.DecodeFor].
func ( *InputResponse) ( []byte) error {
	* = InputResponse{raw: append(json.RawMessage(nil), ...)}
	return nil
}

// DecodeFor resolves the response against the method of the request it
// answers, populating the matching variant.
func ( *InputResponse) ( MCPMethod) error {
	if len(.raw) == 0 {
		return nil
	}
	switch  {
	case MethodElicitationCreate:
		var  ElicitationResult
		if  := json.Unmarshal(.raw, &);  != nil {
			return fmt.Errorf("input response %s: %w", , )
		}
		.Elicitation = &
	case MethodSamplingCreateMessage:
		var  CreateMessageResult
		if  := json.Unmarshal(.raw, &);  != nil {
			return fmt.Errorf("input response %s: %w", , )
		}
		.Sampling = &
	case MethodListRoots:
		var  ListRootsResult
		if  := json.Unmarshal(.raw, &);  != nil {
			return fmt.Errorf("input response %s: %w", , )
		}
		.Roots = &
	default:
		return fmt.Errorf("unsupported input response method %q", )
	}
	return nil
}

// InputRequests maps server-assigned identifiers to the requests a client must
// fulfil before retrying the original call.
type InputRequests map[string]InputRequest

// InputResponses maps the identifiers from an [InputRequests] map to the
// client's answers.
type InputResponses map[string]InputResponse

// DecodeFor resolves every response in the map against the methods of the
// corresponding requests.
func ( InputResponses) ( InputRequests) error {
	for ,  := range  {
		,  := []
		if ! {
			continue
		}
		if  := .DecodeFor(.Method);  != nil {
			return fmt.Errorf("input response %q: %w", , )
		}
		[] = 
	}
	return nil
}

// MultiRoundTripResult carries the multi round-trip fields on results that may
// ask the client for more input before completing. It is embedded in
// [CallToolResult], [GetPromptResult], and [ReadResourceResult].
type MultiRoundTripResult struct {
	// InputRequests are the requests the client must fulfil before retrying.
	// Present only when ResultType is [ResultTypeInputRequired].
	InputRequests InputRequests `json:"inputRequests,omitempty"`

	// RequestState is an opaque token the client must pass back verbatim when
	// it retries the original request. Clients MUST NOT interpret it.
	RequestState string `json:"requestState,omitempty"`
}

// InputRequiredResult is returned by a server to indicate that it needs
// additional input before it can complete a request.
//
// At least one of InputRequests or RequestState must be present. An empty
// InputRequests map with a RequestState is a load-shedding signal: the client
// should retry the request unchanged, echoing the state back.
type InputRequiredResult struct {
	Result
	MultiRoundTripResult
}

// NewInputRequiredResult builds a result asking the client for more input
// before the request can be completed. requestState is echoed back by the
// client on retry and may be empty.
func ( InputRequests,  string) *InputRequiredResult {
	return &InputRequiredResult{
		Result: Result{ResultType: ResultTypeInputRequired},
		MultiRoundTripResult: MultiRoundTripResult{
			InputRequests: ,
			RequestState:  ,
		},
	}
}

// MultiRoundTripParams carries the client's answers to a previous
// [InputRequiredResult] on a retry of the original request. It is embedded in
// the params of every request that may take part in a multi round-trip
// exchange.
type MultiRoundTripParams struct {
	// InputResponses answers the requests from a previous
	// [InputRequiredResult]. Each key present in that result's InputRequests
	// map must appear here.
	InputResponses InputResponses `json:"inputResponses,omitempty"`

	// RequestState echoes back, verbatim, the opaque state from a previous
	// [InputRequiredResult].
	RequestState string `json:"requestState,omitempty"`
}

// NeedsInput reports whether the result asks the client for more input before
// the original request can complete.
func ( *InputRequiredResult) () bool {
	return  != nil && .ResultType == ResultTypeInputRequired
}

// NeedsInput reports whether the result asks the client for more input before
// the original request can complete.
func ( *CallToolResult) () bool {
	return  != nil && .ResultType == ResultTypeInputRequired
}

// NeedsInput reports whether the result asks the client for more input before
// the original request can complete.
func ( *GetPromptResult) () bool {
	return  != nil && .ResultType == ResultTypeInputRequired
}

// NeedsInput reports whether the result asks the client for more input before
// the original request can complete.
func ( *ReadResourceResult) () bool {
	return  != nil && .ResultType == ResultTypeInputRequired
}