Debian Codegraph @

debian/go/src/github.com/modelcontextprotocol/go-sdk/internal/jsonrpc2/messages.go

raw symbols SCIP
1 // Copyright 2018 The Go MCP SDK Authors. All rights reserved.
2 // Use of this source code is governed by an MIT-style
3 // license that can be found in the LICENSE file.
4
5 package jsonrpc2
6
7 import (
8 "bytes"
9 "encoding/json"
10 "errors"
11 "fmt"
12
13 internaljson "github.com/modelcontextprotocol/go-sdk/internal/json"
14 )
15
16 // ID is a Request identifier, which is defined by the spec to be a string, integer, or null.
17 // https://www.jsonrpc.org/specification#request_object
18 type ID struct {
19 value any
20 }
21
22 // MakeID coerces the given Go value to an ID. The value should be the
23 // default JSON marshaling of a Request identifier: nil, float64, or string.
24 //
25 // Returns an error if the value type was not a valid Request ID type.
26 //
27 // TODO: ID can't be a json.Marshaler/Unmarshaler, because we want to omitzero.
28 // Simplify this package by making ID json serializable once we can rely on
29 // omitzero.
30 func MakeID(v any) (ID, error) {
31 switch v := v.(type) {
32 case nil:
33 return ID{}, nil
34 case float64:
35 return Int64ID(int64(v)), nil
36 case string:
37 return StringID(v), nil
38 }
39 return ID{}, fmt.Errorf("%w: invalid ID type %T", ErrParse, v)
40 }
41
42 // Message is the interface to all jsonrpc2 message types.
43 // They share no common functionality, but are a closed set of concrete types
44 // that are allowed to implement this interface. The message types are *Request
45 // and *Response.
46 type Message interface {
47 // marshal builds the wire form from the API form.
48 // It is private, which makes the set of Message implementations closed.
49 marshal(to *wireCombined)
50 }
51
52 // Request is a Message sent to a peer to request behavior.
53 // If it has an ID it is a call, otherwise it is a notification.
54 type Request struct {
55 // ID of this request, used to tie the Response back to the request.
56 // This will be nil for notifications.
57 ID ID
58 // Method is a string containing the method name to invoke.
59 Method string
60 // Params is either a struct or an array with the parameters of the method.
61 Params json.RawMessage
62 // Extra is additional information that does not appear on the wire. It can be
63 // used to pass information from the application to the underlying transport.
64 Extra any
65 }
66
67 // Response is a Message used as a reply to a call Request.
68 // It will have the same ID as the call it is a response to.
69 type Response struct {
70 // result is the content of the response.
71 Result json.RawMessage
72 // err is set only if the call failed.
73 Error error
74 // id of the request this is a response to.
75 ID ID
76 // Extra is additional information that does not appear on the wire. It can be
77 // used to pass information from the underlying transport to the application.
78 Extra any
79 }
80
81 // StringID creates a new string request identifier.
82 func StringID(s string) ID { return ID{value: s} }
83
84 // Int64ID creates a new integer request identifier.
85 func Int64ID(i int64) ID { return ID{value: i} }
86
87 // IsValid returns true if the ID is a valid identifier.
88 // The default value for ID will return false.
89 func (id ID) IsValid() bool { return id.value != nil }
90
91 // Raw returns the underlying value of the ID.
92 func (id ID) Raw() any { return id.value }
93
94 // NewNotification constructs a new Notification message for the supplied
95 // method and parameters.
96 func NewNotification(method string, params any) (*Request, error) {
97 p, merr := marshalToRaw(params)
98 return &Request{Method: method, Params: p}, merr
99 }
100
101 // NewCall constructs a new Call message for the supplied ID, method and
102 // parameters.
103 func NewCall(id ID, method string, params any) (*Request, error) {
104 p, merr := marshalToRaw(params)
105 return &Request{ID: id, Method: method, Params: p}, merr
106 }
107
108 func (msg *Request) IsCall() bool { return msg.ID.IsValid() }
109
110 func (msg *Request) marshal(to *wireCombined) {
111 to.ID = msg.ID.value
112 to.Method = msg.Method
113 to.Params = msg.Params
114 }
115
116 // NewResponse constructs a new Response message that is a reply to the
117 // supplied. If err is set result may be ignored.
118 func NewResponse(id ID, result any, rerr error) (*Response, error) {
119 r, merr := marshalToRaw(result)
120 return &Response{ID: id, Result: r, Error: rerr}, merr
121 }
122
123 func (msg *Response) marshal(to *wireCombined) {
124 to.ID = msg.ID.value
125 to.Error = toWireError(msg.Error)
126 to.Result = msg.Result
127 }
128
129 func toWireError(err error) *WireError {
130 if err == nil {
131 // no error, the response is complete
132 return nil
133 }
134 if err, ok := err.(*WireError); ok {
135 // already a wire error, just use it
136 return err
137 }
138 result := &WireError{Message: err.Error()}
139 var wrapped *WireError
140 if errors.As(err, &wrapped) {
141 // if we wrapped a wire error, keep the code from the wrapped error
142 // but the message from the outer error
143 result.Code = wrapped.Code
144 }
145 return result
146 }
147
148 func EncodeMessage(msg Message) ([]byte, error) {
149 wire := wireCombined{VersionTag: wireVersion}
150 msg.marshal(&wire)
151 data, err := jsonMarshal(&wire)
152 if err != nil {
153 return nil, fmt.Errorf("marshaling jsonrpc message: %w", err)
154 }
155 return data, nil
156 }
157
158 // EncodeIndent is like EncodeMessage, but honors indents.
159 // TODO(rfindley): refactor so that this concern is handled independently.
160 // Perhaps we should pass in a json.Encoder?
161 func EncodeIndent(msg Message, prefix, indent string) ([]byte, error) {
162 wire := wireCombined{VersionTag: wireVersion}
163 msg.marshal(&wire)
164 var buf bytes.Buffer
165 enc := json.NewEncoder(&buf)
166 enc.SetEscapeHTML(false)
167 enc.SetIndent(prefix, indent)
168 if err := enc.Encode(&wire); err != nil {
169 return nil, fmt.Errorf("marshaling jsonrpc message: %w", err)
170 }
171 return bytes.TrimRight(buf.Bytes(), "\n"), nil
172 }
173
174 func DecodeMessage(data []byte) (Message, error) {
175 msg := wireCombined{}
176 if err := internaljson.Unmarshal(data, &msg); err != nil {
177 return nil, fmt.Errorf("unmarshaling jsonrpc message: %w", err)
178 }
179 if msg.VersionTag != wireVersion {
180 return nil, fmt.Errorf("invalid message version tag %q; expected %q", msg.VersionTag, wireVersion)
181 }
182 id, err := MakeID(msg.ID)
183 if err != nil {
184 return nil, err
185 }
186 if msg.Method != "" {
187 // has a method, must be a call
188 return &Request{
189 Method: msg.Method,
190 ID: id,
191 Params: msg.Params,
192 }, nil
193 }
194 // no method, should be a response
195 if !id.IsValid() {
196 return nil, ErrInvalidRequest
197 }
198 resp := &Response{
199 ID: id,
200 Result: msg.Result,
201 }
202 // we have to check if msg.Error is nil to avoid a typed error
203 if msg.Error != nil {
204 resp.Error = msg.Error
205 }
206 return resp, nil
207 }
208
209 func marshalToRaw(obj any) (json.RawMessage, error) {
210 if obj == nil {
211 return nil, nil
212 }
213 data, err := jsonMarshal(obj)
214 if err != nil {
215 return nil, err
216 }
217 return json.RawMessage(data), nil
218 }
219
220 // jsonMarshal marshals obj to JSON like json.Marshal but without HTML escaping.
221 func jsonMarshal(obj any) ([]byte, error) {
222 var buf bytes.Buffer
223 enc := json.NewEncoder(&buf)
224 enc.SetEscapeHTML(false)
225 if err := enc.Encode(obj); err != nil {
226 return nil, err
227 }
228 // json.Encoder.Encode adds a trailing newline. Trim it to be consistent with json.Marshal.
229 return bytes.TrimRight(buf.Bytes(), "\n"), nil
230 }