The transport, the handshake and the Host API calls now come from the shared SDK, so this package only routes channel messages and the host's JSON-RPC error codes reach the MCP tools.
187 lines
5.2 KiB
Go
187 lines
5.2 KiB
Go
package sidecar
|
|
|
|
import (
|
|
"bufio"
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"sort"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/Nwflower/reims-go/pkg/pluginsdk"
|
|
)
|
|
|
|
type recordingHandler struct {
|
|
mu sync.Mutex
|
|
handled []string
|
|
closed []string
|
|
}
|
|
|
|
func (h *recordingHandler) Handle(_ context.Context, channel, session string, _ json.RawMessage) (json.RawMessage, error) {
|
|
h.mu.Lock()
|
|
defer h.mu.Unlock()
|
|
h.handled = append(h.handled, channel+"/"+session)
|
|
return json.RawMessage(`{"ok":true}`), nil
|
|
}
|
|
|
|
func (h *recordingHandler) SessionClosed(channel, session string) {
|
|
h.mu.Lock()
|
|
defer h.mu.Unlock()
|
|
h.closed = append(h.closed, channel+"/"+session)
|
|
}
|
|
|
|
func (h *recordingHandler) state() ([]string, []string) {
|
|
h.mu.Lock()
|
|
defer h.mu.Unlock()
|
|
return append([]string(nil), h.handled...), append([]string(nil), h.closed...)
|
|
}
|
|
|
|
type rpcEnvelope struct {
|
|
JSONRPC string `json:"jsonrpc"`
|
|
ID json.RawMessage `json:"id,omitempty"`
|
|
Method string `json:"method,omitempty"`
|
|
Params json.RawMessage `json:"params,omitempty"`
|
|
Result json.RawMessage `json:"result,omitempty"`
|
|
Error *struct {
|
|
Code int `json:"code"`
|
|
Message string `json:"message"`
|
|
} `json:"error,omitempty"`
|
|
}
|
|
|
|
func writeFrame(w io.Writer, v any) error {
|
|
raw, err := json.Marshal(v)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
_, err = fmt.Fprintf(w, "Content-Length: %d\r\n\r\n%s", len(raw), raw)
|
|
return err
|
|
}
|
|
|
|
func readFrame(r *bufio.Reader) (rpcEnvelope, error) {
|
|
length := -1
|
|
for {
|
|
line, err := r.ReadString('\n')
|
|
if err != nil {
|
|
return rpcEnvelope{}, err
|
|
}
|
|
line = strings.TrimRight(line, "\r\n")
|
|
if line == "" {
|
|
break
|
|
}
|
|
key, value, ok := strings.Cut(line, ":")
|
|
if ok && strings.EqualFold(strings.TrimSpace(key), "Content-Length") {
|
|
if _, err := fmt.Sscanf(strings.TrimSpace(value), "%d", &length); err != nil {
|
|
return rpcEnvelope{}, err
|
|
}
|
|
}
|
|
}
|
|
if length < 0 {
|
|
return rpcEnvelope{}, errors.New("frame is missing Content-Length")
|
|
}
|
|
frame := make([]byte, length)
|
|
if _, err := io.ReadFull(r, frame); err != nil {
|
|
return rpcEnvelope{}, err
|
|
}
|
|
var env rpcEnvelope
|
|
return env, json.Unmarshal(frame, &env)
|
|
}
|
|
|
|
func TestChannelsAreRoutedAndUnknownOnesRefused(t *testing.T) {
|
|
handler := &recordingHandler{}
|
|
inR, inW := io.Pipe()
|
|
outR, outW := io.Pipe()
|
|
server := NewWithIO(inR, outW, handler)
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
defer cancel()
|
|
go func() { _ = server.Serve(ctx) }()
|
|
|
|
requests := []rpcEnvelope{
|
|
{JSONRPC: "2.0", ID: json.RawMessage("1"), Method: "plugin/initialize", Params: json.RawMessage(`{"pluginId":"reims.agent"}`)},
|
|
{JSONRPC: "2.0", ID: json.RawMessage("2"), Method: "channel/mcp/message", Params: json.RawMessage(`{"message":{},"session":"a"}`)},
|
|
{JSONRPC: "2.0", ID: json.RawMessage("3"), Method: "channel/mcp-dev/message", Params: json.RawMessage(`{"message":{}}`)},
|
|
{JSONRPC: "2.0", Method: "channel/mcp/closed", Params: json.RawMessage(`{"session":"a"}`)},
|
|
{JSONRPC: "2.0", ID: json.RawMessage("4"), Method: "channel/other/message", Params: json.RawMessage(`{"message":{}}`)},
|
|
}
|
|
go func() {
|
|
for _, req := range requests {
|
|
if err := writeFrame(inW, req); err != nil {
|
|
return
|
|
}
|
|
}
|
|
}()
|
|
|
|
reader := bufio.NewReader(outR)
|
|
responses := map[string]rpcEnvelope{}
|
|
for range 4 {
|
|
env, err := readFrame(reader)
|
|
if err != nil {
|
|
t.Fatalf("read response: %v", err)
|
|
}
|
|
responses[strings.TrimSpace(string(env.ID))] = env
|
|
}
|
|
|
|
// The SDK dispatches inbound methods concurrently, so the two channel
|
|
// messages may be handled in either order.
|
|
handled, closed := handler.state()
|
|
sort.Strings(handled)
|
|
if strings.Join(handled, ",") != "mcp-dev/,mcp/a" || strings.Join(closed, ",") != "mcp/a" {
|
|
t.Fatalf("handled=%v closed=%v", handled, closed)
|
|
}
|
|
if !bytes.Contains(responses["1"].Result, []byte(`"channels":["mcp","mcp-dev"]`)) {
|
|
t.Fatalf("initialize = %s", responses["1"].Result)
|
|
}
|
|
for _, id := range []string{"2", "3"} {
|
|
if !bytes.Contains(responses[id].Result, []byte(`"message":{"ok":true}`)) {
|
|
t.Fatalf("channel reply %s = %s", id, responses[id].Result)
|
|
}
|
|
}
|
|
if responses["4"].Error == nil {
|
|
t.Fatal("a channel this sidecar does not serve must be refused")
|
|
}
|
|
}
|
|
|
|
func TestHostCallKeepsTheErrorCode(t *testing.T) {
|
|
inR, inW := io.Pipe()
|
|
outR, outW := io.Pipe()
|
|
server := NewWithIO(inR, outW, nil)
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
defer cancel()
|
|
go func() { _ = server.Serve(ctx) }()
|
|
|
|
go func() {
|
|
reader := bufio.NewReader(outR)
|
|
for {
|
|
env, err := readFrame(reader)
|
|
if err != nil {
|
|
return
|
|
}
|
|
if env.Method == "" || len(env.ID) == 0 {
|
|
continue
|
|
}
|
|
_ = writeFrame(inW, rpcEnvelope{
|
|
JSONRPC: "2.0",
|
|
ID: env.ID,
|
|
Error: &struct {
|
|
Code int `json:"code"`
|
|
Message string `json:"message"`
|
|
}{Code: -32602, Message: "host/console.key: unknown field"},
|
|
})
|
|
return
|
|
}
|
|
}()
|
|
|
|
callCtx, callCancel := context.WithTimeout(ctx, 5*time.Second)
|
|
defer callCancel()
|
|
err := HostClient{Server: server}.Call(callCtx, "host/console.key", map[string]any{"vm": "a"}, nil)
|
|
var sdkErr *pluginsdk.Error
|
|
if !errors.As(err, &sdkErr) || sdkErr.Code != pluginsdk.InvalidParams {
|
|
t.Fatalf("err = %v, want an SDK error with code %d", err, pluginsdk.InvalidParams)
|
|
}
|
|
}
|