Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
kardolus
GitHub Repository: kardolus/chatgpt-cli
Path: blob/main/api/mcp.go
3434 views
1
package api
2
3
import (
4
"encoding/json"
5
"fmt"
6
"strings"
7
)
8
9
type MCPError struct {
10
// JSON-RPC spec: code is an integer.
11
// We normalize it into a string to keep the rest of your code stable.
12
Code string `json:"-"`
13
Message string `json:"message"`
14
Data map[string]interface{} `json:"data,omitempty"`
15
}
16
17
func (e *MCPError) UnmarshalJSON(b []byte) error {
18
// accept code as number or string
19
var aux struct {
20
Code json.RawMessage `json:"code"`
21
Message string `json:"message"`
22
Data map[string]interface{} `json:"data,omitempty"`
23
}
24
25
if err := json.Unmarshal(b, &aux); err != nil {
26
return err
27
}
28
29
e.Message = aux.Message
30
e.Data = aux.Data
31
32
// Try int first (correct JSON-RPC)
33
var n int
34
if err := json.Unmarshal(aux.Code, &n); err == nil {
35
e.Code = fmt.Sprintf("%d", n)
36
return nil
37
}
38
39
// Then try string (some servers may do this)
40
var s string
41
if err := json.Unmarshal(aux.Code, &s); err == nil {
42
e.Code = s
43
return nil
44
}
45
46
// Last resort: keep raw
47
e.Code = string(aux.Code)
48
return nil
49
}
50
51
func (e *MCPError) Error() string {
52
if e == nil {
53
return ""
54
}
55
if e.Code == "" {
56
return e.Message
57
}
58
return fmt.Sprintf("mcp error %s: %s", e.Code, e.Message)
59
}
60
61
type MCPMessage struct {
62
// JSON-RPC request/response fields
63
JSONRPC string `json:"jsonrpc,omitempty"`
64
ID string `json:"id,omitempty"`
65
Method string `json:"method,omitempty"`
66
Params json.RawMessage `json:"params,omitempty"`
67
68
// JSON-RPC response fields
69
Result json.RawMessage `json:"result,omitempty"`
70
Error *MCPError `json:"error,omitempty"`
71
}
72
73
type MCPResponse struct {
74
Message MCPMessage `json:"-"`
75
Headers map[string]string `json:"-"`
76
Status int `json:"-"`
77
}
78
79
func (r MCPResponse) Header(key string) (string, bool) {
80
for k, v := range r.Headers {
81
if strings.EqualFold(k, key) {
82
return v, true
83
}
84
}
85
return "", false
86
}
87
88
type MCPRequest struct {
89
Endpoint string
90
Headers map[string]string
91
Tool string
92
Params map[string]interface{}
93
}
94
95
type HTTPTransport struct {
96
Headers map[string]string
97
}
98
99