51 lines
1.5 KiB
Go
51 lines
1.5 KiB
Go
package mcp
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
)
|
|
|
|
// rpcRequest is a JSON-RPC 2.0 request. Notifications omit ID so the field is
|
|
// tagged omitempty. Params is any so callers pass a struct or a JSON object.
|
|
type rpcRequest struct {
|
|
JSONRPC string `json:"jsonrpc"`
|
|
ID any `json:"id,omitempty"`
|
|
Method string `json:"method"`
|
|
Params any `json:"params,omitempty"`
|
|
}
|
|
|
|
// rpcResponse is a JSON-RPC 2.0 response. Result is kept raw until the caller
|
|
// decodes it into the concrete result type.
|
|
type rpcResponse struct {
|
|
JSONRPC string `json:"jsonrpc"`
|
|
ID any `json:"id,omitempty"`
|
|
Result json.RawMessage `json:"result,omitempty"`
|
|
Error *rpcError `json:"error,omitempty"`
|
|
}
|
|
|
|
// rpcError is a JSON-RPC error object. It satisfies error so it can be wrapped
|
|
// and surfaced with %w.
|
|
type rpcError struct {
|
|
Code int `json:"code"`
|
|
Message string `json:"message"`
|
|
Data any `json:"data,omitempty"`
|
|
}
|
|
|
|
// Error implements error.
|
|
func (e *rpcError) Error() string {
|
|
return fmt.Sprintf("code %d: %s", e.Code, e.Message)
|
|
}
|
|
|
|
// encodeRequest marshals a JSON-RPC request. An id of nil produces a
|
|
// notification (no id field).
|
|
func encodeRequest(id any, method string, params any) ([]byte, error) {
|
|
return json.Marshal(rpcRequest{JSONRPC: "2.0", ID: id, Method: method, Params: params})
|
|
}
|
|
|
|
// decodeIDString reports whether res carries the string id expected for a JSON
|
|
// string id request.
|
|
func decodeIDString(res rpcResponse, id string) bool {
|
|
s, ok := res.ID.(string)
|
|
return ok && s == id
|
|
}
|