summaryrefslogtreecommitdiff
path: root/internal/mcp/transport.go
blob: 5119d2c715a28b1eb433b1e5b4f5637cfcea9029 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// MCP transport utilities for reading and writing JSON-RPC messages
// using newline-delimited JSON (JSONL) as required by the MCP stdio protocol.
package mcp

import (
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"strings"
)

// readMessage reads a newline-delimited JSON-RPC message from the input stream.
// Returns the raw JSON bytes. Follows the MCP stdio transport specification
// which uses newline-delimited JSON (JSONL), not LSP-style Content-Length framing.
// Uses the server's bufio.Reader (s.in) to avoid losing buffered data between calls.
func (s *Server) readMessage() ([]byte, error) {
	for {
		line, err := s.in.ReadString('\n')
		if err != nil && len(line) == 0 {
			if errors.Is(err, io.EOF) {
				return nil, io.EOF
			}
			return nil, fmt.Errorf("read error: %w", err)
		}
		line = strings.TrimSpace(line)
		if line == "" {
			// If we hit EOF on an empty line, propagate it
			if errors.Is(err, io.EOF) {
				return nil, io.EOF
			}
			continue // skip empty lines
		}
		return []byte(line), nil
	}
}

// writeMessage writes a JSON-RPC response as newline-delimited JSON.
// Thread-safe via mutex lock.
func (s *Server) writeMessage(v any) error {
	s.outMu.Lock()
	defer s.outMu.Unlock()

	data, err := json.Marshal(v)
	if err != nil {
		return fmt.Errorf("marshal error: %w", err)
	}
	// Write JSON followed by newline (JSONL format)
	if _, err := s.out.Write(data); err != nil {
		return fmt.Errorf("write body error: %w", err)
	}
	if _, err := io.WriteString(s.out, "\n"); err != nil {
		return fmt.Errorf("write newline error: %w", err)
	}
	return nil
}