Skip to content

Commit e9c37a3

Browse files
committed
Add keep-alive header to sse handler
1 parent 57f84e6 commit e9c37a3

File tree

1 file changed

+17
-7
lines changed

1 file changed

+17
-7
lines changed

common/toolcall/mcp_sse_transport.cpp

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,9 @@ static size_t sse_callback(char * data, size_t size, size_t nmemb, void * client
3838
return transport->process_sse_data(data, len);
3939
}
4040

41+
// Taken from specification:
42+
// https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation
43+
//
4144
void toolcall::mcp_sse_transport::parse_field_value(std::string field, std::string value) {
4245
if (field == "event") {
4346
// Set the event type buffer to field value.
@@ -72,7 +75,11 @@ void toolcall::mcp_sse_transport::parse_field_value(std::string field, std::stri
7275
}
7376

7477
void toolcall::mcp_sse_transport::on_endpoint_event() {
75-
// TODO: Initialize endpoint_ but it won't be used until "send" is called
78+
endpoint_ = curl_easy_init();
79+
if (! endpoint_) {
80+
// Log error and abort
81+
}
82+
curl_easy_setopt(endpoint_, CURLOPT_URL, event_.data.c_str());
7683
}
7784

7885
void toolcall::mcp_sse_transport::on_message_event() {
@@ -133,25 +140,28 @@ size_t toolcall::mcp_sse_transport::sse_read(const char * data, size_t len) {
133140
}
134141

135142
void toolcall::mcp_sse_transport::sse_background() {
136-
// This is only place the sse_ member should be accessed.
137-
// Set options using curl_easy_setopt
138-
// Set up write function which handles the events
139143
sse_ = curl_easy_init();
140-
if (!curl) {
144+
if (! sse_) {
145+
// Log error
141146
std::cerr << "Failed to initialize CURL" << std::endl;
142147
return;
143148
}
144149

145150
curl_easy_setopt(sse_, CURLOPT_URL, server_uri_.c_str());
151+
curl_easy_setopt(sse_, CURLOPT_TCP_KEEPALIVE, 1L);
146152
curl_easy_setopt(sse_, CURLOPT_WRITEFUNCTION, sse_callback);
147153
curl_easy_setopt(sse_, CURLOPT_WRITEDATA, this);
148-
curl_easy_setopt(sse_, CURLOPT_NOPROGRESS, 1L);
149-
curl_easy_setopt(sse_, CURLOPT_HTTPHEADER, headers_.get());
154+
155+
struct curl_slist *headers = NULL;
156+
headers = curl_slist_append(headers, "Connection: keep-alive");
157+
curl_easy_setopt(sse_, CURLOPT_HTTPHEADER, headers);
150158

151159
CURLcode res = curl_easy_perform(curl);
152160
if (res != CURLE_OK) {
161+
// Log error
153162
std::cerr << "CURL error: " << curl_easy_strerror(res) << std::endl;
154163
}
155164

165+
curl_slist_free_all(headers);
156166
curl_easy_cleanup(curl);
157167
}

0 commit comments

Comments
 (0)