-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp_request.go
More file actions
311 lines (270 loc) · 7.55 KB
/
Copy pathhttp_request.go
File metadata and controls
311 lines (270 loc) · 7.55 KB
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
)
const (
maxHTTPResponseLength = 16000
maxHTTPRedirects = 5
defaultHTTPTimeout = 10
)
type httpRequestRequest struct {
URL string
Method string
Headers map[string]string
Body string
TimeoutSeconds int
Reason string
}
type httpRequestResult struct {
Request httpRequestRequest
StatusCode int
StatusText string
Headers map[string]string
Body string
BodyTruncated bool
ExecutionErr string
UserDenied bool
}
func parseHTTPRequestRequest(args map[string]any) (httpRequestRequest, error) {
req := httpRequestRequest{
Method: "GET",
TimeoutSeconds: defaultHTTPTimeout,
Headers: make(map[string]string),
}
// Required: url
url, err := requiredStringArg(args, "url")
if err != nil {
return req, err
}
req.URL = strings.TrimSpace(url)
if req.URL == "" {
return req, fmt.Errorf("url cannot be empty")
}
// Validate URL has scheme
if !strings.HasPrefix(req.URL, "http://") && !strings.HasPrefix(req.URL, "https://") {
return req, fmt.Errorf("url must include scheme (http:// or https://)")
}
// Optional: method
if v, ok := args["method"]; ok {
if s, ok := v.(string); ok {
method := strings.ToUpper(strings.TrimSpace(s))
// Validate method is one of the allowed values
switch method {
case "GET", "POST", "PUT", "PATCH", "DELETE":
req.Method = method
default:
return req, fmt.Errorf("invalid method '%s': must be one of GET, POST, PUT, PATCH, DELETE", s)
}
}
}
// Optional: headers
if v, ok := args["headers"]; ok {
if headersMap, ok := v.(map[string]any); ok {
for key, val := range headersMap {
if strVal, ok := val.(string); ok {
req.Headers[key] = strVal
}
}
}
}
// Optional: body (ignored for GET and DELETE)
if v, ok := args["body"]; ok {
if s, ok := v.(string); ok {
req.Body = s
}
}
// Validate body is not used with GET or DELETE
if req.Body != "" && (req.Method == "GET" || req.Method == "DELETE") {
return req, fmt.Errorf("body parameter is not allowed for %s requests", req.Method)
}
// Optional: timeout_seconds
if v, ok := args["timeout_seconds"]; ok {
timeout, err := parseInt(v)
if err != nil {
return req, fmt.Errorf("timeout_seconds must be an integer: %w", err)
}
if timeout < 1 || timeout > 60 {
return req, fmt.Errorf("timeout_seconds must be between 1 and 60, got %d", timeout)
}
req.TimeoutSeconds = timeout
}
// Optional: reason
if v, ok := args["reason"]; ok {
if s, ok := v.(string); ok {
req.Reason = strings.TrimSpace(s)
}
}
return req, nil
}
func executeHTTPRequest(req httpRequestRequest) httpRequestResult {
res := httpRequestResult{Request: req}
// Create context with timeout
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(req.TimeoutSeconds)*time.Second)
defer cancel()
// Create HTTP request
var bodyReader io.Reader
if req.Body != "" {
bodyReader = strings.NewReader(req.Body)
}
httpReq, err := http.NewRequestWithContext(ctx, req.Method, req.URL, bodyReader)
if err != nil {
res.ExecutionErr = fmt.Sprintf("failed to create request: %v", err)
return res
}
// Set headers
for key, value := range req.Headers {
httpReq.Header.Set(key, value)
}
// Create client with redirect limit
client := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
if len(via) >= maxHTTPRedirects {
return fmt.Errorf("stopped after %d redirects", maxHTTPRedirects)
}
return nil
},
}
// Execute request
httpResp, err := client.Do(httpReq)
if err != nil {
// Check for specific error types
if ctx.Err() == context.DeadlineExceeded {
res.ExecutionErr = fmt.Sprintf("request timed out after %d seconds", req.TimeoutSeconds)
} else if strings.Contains(err.Error(), "no such host") {
res.ExecutionErr = fmt.Sprintf("DNS resolution failed: %v", err)
} else if strings.Contains(err.Error(), "connection refused") {
res.ExecutionErr = fmt.Sprintf("connection refused: %v", err)
} else {
res.ExecutionErr = fmt.Sprintf("request failed: %v", err)
}
return res
}
defer httpResp.Body.Close()
// Capture status
res.StatusCode = httpResp.StatusCode
res.StatusText = httpResp.Status
// Capture filtered headers
res.Headers = make(map[string]string)
allowedHeaders := []string{"Content-Type", "X-Request-Id", "Location", "WWW-Authenticate"}
for _, header := range allowedHeaders {
if value := httpResp.Header.Get(header); value != "" {
res.Headers[header] = value
}
}
// Read response body
bodyBytes, err := io.ReadAll(httpResp.Body)
if err != nil {
res.ExecutionErr = fmt.Sprintf("failed to read response body: %v", err)
return res
}
bodyStr := string(bodyBytes)
// Truncate if necessary
if len(bodyStr) > maxHTTPResponseLength {
bodyStr = bodyStr[:maxHTTPResponseLength]
res.BodyTruncated = true
}
// Pretty-print JSON if Content-Type indicates JSON
contentType := httpResp.Header.Get("Content-Type")
if strings.Contains(contentType, "application/json") || strings.Contains(contentType, "text/json") {
var jsonData any
if err := json.Unmarshal([]byte(bodyStr), &jsonData); err == nil {
prettyJSON, err := json.MarshalIndent(jsonData, "", " ")
if err == nil {
bodyStr = string(prettyJSON)
// Re-check length after pretty-printing
if len(bodyStr) > maxHTTPResponseLength {
bodyStr = bodyStr[:maxHTTPResponseLength]
res.BodyTruncated = true
}
}
}
}
res.Body = bodyStr
return res
}
func (res httpRequestResult) toToolResponse() map[string]any {
if res.ExecutionErr != "" {
return map[string]any{
"error": map[string]any{
"message": res.ExecutionErr,
},
}
}
if res.UserDenied {
return map[string]any{
"error": map[string]any{
"message": "request denied by user",
},
}
}
response := map[string]any{
"status_code": res.StatusCode,
"status_text": res.StatusText,
"headers": res.Headers,
"body": res.Body,
}
if res.BodyTruncated {
response["body_truncated"] = true
response["truncation_note"] = fmt.Sprintf("Response body was truncated to %d characters", maxHTTPResponseLength)
}
return response
}
func printHTTPRequestCall(req httpRequestRequest) {
uiPrintf("\n🌐 HTTP Request\n")
uiPrintf(" Method: %s\n", req.Method)
uiPrintf(" URL: %s\n", req.URL)
if len(req.Headers) > 0 {
uiPrintf(" Headers:\n")
for key, value := range req.Headers {
uiPrintf(" %s: %s\n", key, value)
}
}
if req.Body != "" {
uiPrintf(" Body: %s\n", truncateForDisplay(req.Body, 200))
}
if req.Reason != "" {
uiPrintf(" Reason: %s\n", req.Reason)
}
}
func askForHTTPRequestApproval() bool {
if TUIApprovalHook != nil {
return TUIApprovalHook(" Send request? [y/N]: ")
}
uiPrint(" Send request? [y/N]: ")
return askYesNo()
}
func printHTTPRequestDenied() {
uiPrintln(" ❌ Request denied by user")
}
func printHTTPRequestResult(res httpRequestResult) {
if res.ExecutionErr != "" {
uiPrintf(" ❌ Error: %s\n", res.ExecutionErr)
return
}
uiPrintf(" ✓ Status: %s\n", res.StatusText)
if len(res.Headers) > 0 {
uiPrintf(" Response Headers:\n")
for key, value := range res.Headers {
uiPrintf(" %s: %s\n", key, value)
}
}
if res.Body != "" {
uiPrintf(" Body: %s\n", truncateForDisplay(res.Body, 500))
}
if res.BodyTruncated {
uiPrintf(" ⚠️ Response truncated to %d characters\n", maxHTTPResponseLength)
}
}
func truncateForDisplay(s string, max int) string {
if len(s) <= max {
return s
}
return s[:max] + "..."
}
// Made with Bob