|
| 1 | +package transport |
| 2 | + |
| 3 | +import ( |
| 4 | + "bufio" |
| 5 | + "bytes" |
| 6 | + "encoding/json" |
| 7 | + "fmt" |
| 8 | + "io" |
| 9 | + "net/http" |
| 10 | + "net/url" |
| 11 | + "os" |
| 12 | + "strings" |
| 13 | + "time" |
| 14 | +) |
| 15 | + |
| 16 | +// HTTP implements the Transport interface by communicating with a MCP server over HTTP using JSON-RPC. |
| 17 | +type HTTP struct { |
| 18 | + eventCh chan string |
| 19 | + address string |
| 20 | + debug bool |
| 21 | + nextID int |
| 22 | +} |
| 23 | + |
| 24 | +// NewHTTP creates a new Http transport that will execute the given command. |
| 25 | +// It communicates with the command using JSON-RPC over HTTP. |
| 26 | +// Currently Http transport is implements MCP's Final draft version 2024-11-05, |
| 27 | +// https://spec.modelcontextprotocol.io/specification/2024-11-05/basic/transports/#http-with-sse |
| 28 | +func NewHTTP(address string) (*HTTP, error) { |
| 29 | + debug := os.Getenv("MCP_DEBUG") == "1" |
| 30 | + |
| 31 | + _, uriErr := url.ParseRequestURI(address) |
| 32 | + if uriErr != nil { |
| 33 | + return nil, fmt.Errorf("invalid address: %w", uriErr) |
| 34 | + } |
| 35 | + |
| 36 | + resp, err := http.Get(address + "/sse") |
| 37 | + if err != nil { |
| 38 | + return nil, fmt.Errorf("error sending request: %w", err) |
| 39 | + } |
| 40 | + |
| 41 | + eventCh := make(chan string, 1) |
| 42 | + |
| 43 | + go func() { |
| 44 | + defer func() { |
| 45 | + if closeErr := resp.Body.Close(); closeErr != nil { |
| 46 | + fmt.Fprintf(os.Stderr, "Failed to close response body: %v\n", closeErr) |
| 47 | + } |
| 48 | + }() |
| 49 | + |
| 50 | + reader := bufio.NewReader(resp.Body) |
| 51 | + for { |
| 52 | + line, lineErr := reader.ReadString('\n') |
| 53 | + if lineErr != nil { |
| 54 | + fmt.Fprintf(os.Stderr, "SSE read error: %v\n", lineErr) |
| 55 | + return |
| 56 | + } |
| 57 | + line = strings.TrimSpace(line) |
| 58 | + if debug { |
| 59 | + fmt.Fprintf(os.Stderr, "DEBUG: Received SSE: %s\n", line) |
| 60 | + } |
| 61 | + if strings.HasPrefix(line, "data:") { |
| 62 | + data := strings.TrimSpace(line[5:]) |
| 63 | + select { |
| 64 | + case eventCh <- data: |
| 65 | + default: |
| 66 | + } |
| 67 | + } |
| 68 | + } |
| 69 | + }() |
| 70 | + |
| 71 | + // First event we receive from SSE is the message address. We will use this endpoint to keep |
| 72 | + // a session alive. |
| 73 | + var messageAddress string |
| 74 | + select { |
| 75 | + case msg := <-eventCh: |
| 76 | + messageAddress = msg |
| 77 | + case <-time.After(10 * time.Second): |
| 78 | + return nil, fmt.Errorf("timeout waiting for SSE response") |
| 79 | + } |
| 80 | + |
| 81 | + return &HTTP{ |
| 82 | + // Use the SSE message address as the base address for the HTTP transport |
| 83 | + address: address + messageAddress, |
| 84 | + nextID: 1, |
| 85 | + debug: debug, |
| 86 | + eventCh: eventCh, |
| 87 | + }, nil |
| 88 | +} |
| 89 | + |
| 90 | +// Execute implements the Transport via JSON-RPC over HTTP. |
| 91 | +func (t *HTTP) Execute(method string, params any) (map[string]any, error) { |
| 92 | + if t.debug { |
| 93 | + fmt.Fprintf(os.Stderr, "DEBUG: Connecting to server: %s\n", t.address) |
| 94 | + } |
| 95 | + |
| 96 | + request := Request{ |
| 97 | + JSONRPC: "2.0", |
| 98 | + Method: method, |
| 99 | + ID: t.nextID, |
| 100 | + Params: params, |
| 101 | + } |
| 102 | + t.nextID++ |
| 103 | + |
| 104 | + requestJSON, err := json.Marshal(request) |
| 105 | + if err != nil { |
| 106 | + return nil, fmt.Errorf("error marshaling request: %w", err) |
| 107 | + } |
| 108 | + |
| 109 | + requestJSON = append(requestJSON, '\n') |
| 110 | + |
| 111 | + if t.debug { |
| 112 | + fmt.Fprintf(os.Stderr, "DEBUG: Sending request: %s\n", string(requestJSON)) |
| 113 | + } |
| 114 | + |
| 115 | + resp, err := http.Post(t.address, "application/json", bytes.NewBuffer(requestJSON)) |
| 116 | + if err != nil { |
| 117 | + return nil, fmt.Errorf("error sending request: %w", err) |
| 118 | + } |
| 119 | + |
| 120 | + if t.debug { |
| 121 | + fmt.Fprintf(os.Stderr, "DEBUG: Sent request to server\n") |
| 122 | + } |
| 123 | + |
| 124 | + defer func() { |
| 125 | + if closeErr := resp.Body.Close(); closeErr != nil { |
| 126 | + fmt.Fprintf(os.Stderr, "Failed to close response body: %v\n", closeErr) |
| 127 | + } |
| 128 | + }() |
| 129 | + |
| 130 | + body, err := io.ReadAll(resp.Body) |
| 131 | + if err != nil { |
| 132 | + return nil, fmt.Errorf("error reading response: %w", err) |
| 133 | + } |
| 134 | + |
| 135 | + if t.debug { |
| 136 | + fmt.Fprintf(os.Stderr, "DEBUG: Read from server: %s\n", string(body)) |
| 137 | + } |
| 138 | + |
| 139 | + if len(body) == 0 { |
| 140 | + return nil, fmt.Errorf("no response from server") |
| 141 | + } |
| 142 | + |
| 143 | + // After sending the request, we listen the SSE channel for the response |
| 144 | + var response Response |
| 145 | + select { |
| 146 | + case msg := <-t.eventCh: |
| 147 | + if unmarshalErr := json.Unmarshal([]byte(msg), &response); unmarshalErr != nil { |
| 148 | + return nil, fmt.Errorf("error unmarshaling response: %w, response: %s", unmarshalErr, msg) |
| 149 | + } |
| 150 | + case <-time.After(10 * time.Second): |
| 151 | + return nil, fmt.Errorf("timeout waiting for SSE response") |
| 152 | + } |
| 153 | + |
| 154 | + if response.Error != nil { |
| 155 | + return nil, fmt.Errorf("RPC error %d: %s", response.Error.Code, response.Error.Message) |
| 156 | + } |
| 157 | + |
| 158 | + if t.debug { |
| 159 | + fmt.Fprintf(os.Stderr, "DEBUG: Successfully parsed response\n") |
| 160 | + } |
| 161 | + |
| 162 | + return response.Result, nil |
| 163 | +} |
0 commit comments