forked from gptscript-ai/gptscript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgetschema.go
285 lines (245 loc) · 7.98 KB
/
getschema.go
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
package openapi
import (
"encoding/json"
"fmt"
"slices"
"strings"
"github.com/getkin/kin-openapi/openapi3"
)
type Parameter struct {
Name string `json:"name"`
Style string `json:"style"`
Explode *bool `json:"explode"`
}
type OperationInfo struct {
Server string `json:"server"`
Path string `json:"path"`
Method string `json:"method"`
BodyContentMIME string `json:"bodyContentMIME"`
SecurityInfos [][]SecurityInfo `json:"securityInfos"`
QueryParams []Parameter `json:"queryParameters"`
PathParams []Parameter `json:"pathParameters"`
HeaderParams []Parameter `json:"headerParameters"`
CookieParams []Parameter `json:"cookieParameters"`
}
var (
supportedMIMETypes = []string{"application/json", "application/x-www-form-urlencoded", "multipart/form-data"}
supportedSecurityTypes = []string{"apiKey", "http"}
)
const GetSchemaTool = "get-schema"
func GetSupportedMIMETypes() []string {
return supportedMIMETypes
}
func GetSupportedSecurityTypes() []string {
return supportedSecurityTypes
}
// GetSchema returns the JSONSchema and OperationInfo for a particular OpenAPI operation.
// Return values in order: JSONSchema (string), OperationInfo, found (bool), error.
func GetSchema(operationID, defaultHost string, t *openapi3.T) (string, OperationInfo, bool, error) {
arguments := &openapi3.Schema{
Type: &openapi3.Types{"object"},
Properties: openapi3.Schemas{},
Required: []string{},
}
info := OperationInfo{}
// Determine the default server.
var (
defaultServer = defaultHost
err error
)
if len(t.Servers) > 0 {
defaultServer, err = parseServer(t.Servers[0])
if err != nil {
return "", OperationInfo{}, false, err
}
}
var globalSecurity []map[string]struct{}
if t.Security != nil {
for _, item := range t.Security {
current := map[string]struct{}{}
for name := range item {
if scheme, ok := t.Components.SecuritySchemes[name]; ok && slices.Contains(supportedSecurityTypes, scheme.Value.Type) {
current[name] = struct{}{}
}
}
if len(current) > 0 {
globalSecurity = append(globalSecurity, current)
}
}
}
for path, pathItem := range t.Paths.Map() {
// Handle path-level server override, if one exists.
pathServer := defaultServer
if len(pathItem.Servers) > 0 {
pathServer, err = parseServer(pathItem.Servers[0])
if err != nil {
return "", OperationInfo{}, false, err
}
}
for method, operation := range pathItem.Operations() {
if operation.OperationID == operationID {
// Handle operation-level server override, if one exists.
operationServer := pathServer
if operation.Servers != nil && len(*operation.Servers) > 0 {
operationServer, err = parseServer((*operation.Servers)[0])
if err != nil {
return "", OperationInfo{}, false, err
}
}
info.Server = operationServer
info.Path = path
info.Method = method
// We found our operation. Now we need to process it and build the arguments.
// Handle query, path, header, and cookie parameters first.
for _, param := range append(operation.Parameters, pathItem.Parameters...) {
removeRefs(param.Value.Schema)
arg := param.Value.Schema.Value
if arg.Description == "" {
arg.Description = param.Value.Description
}
// Store the arg
arguments.Properties[param.Value.Name] = &openapi3.SchemaRef{Value: arg}
// Check whether it is required
if param.Value.Required {
arguments.Required = append(arguments.Required, param.Value.Name)
}
// Save the parameter to the correct set of params.
p := Parameter{
Name: param.Value.Name,
Style: param.Value.Style,
Explode: param.Value.Explode,
}
switch param.Value.In {
case "query":
info.QueryParams = append(info.QueryParams, p)
case "path":
info.PathParams = append(info.PathParams, p)
case "header":
info.HeaderParams = append(info.HeaderParams, p)
case "cookie":
info.CookieParams = append(info.CookieParams, p)
}
}
// Next, handle the request body, if one exists.
if operation.RequestBody != nil {
for mime, content := range operation.RequestBody.Value.Content {
// Each MIME type needs to be handled individually, so we keep a list of the ones we support.
if !slices.Contains(supportedMIMETypes, mime) {
continue
}
info.BodyContentMIME = mime
removeRefs(content.Schema)
arg := content.Schema.Value
if arg.Description == "" {
arg.Description = content.Schema.Value.Description
}
// Read Only cannot be sent in the request body, so we remove it
for key, property := range arg.Properties {
if property.Value.ReadOnly {
delete(arg.Properties, key)
}
}
// Unfortunately, the request body doesn't contain any good descriptor for it,
// so we just use "requestBodyContent" as the name of the arg.
arguments.Properties["requestBodyContent"] = &openapi3.SchemaRef{Value: arg}
arguments.Required = append(arguments.Required, "requestBodyContent")
break
}
if info.BodyContentMIME == "" {
return "", OperationInfo{}, false, fmt.Errorf("no supported MIME type found for request body in operation %s", operationID)
}
}
// See if there is any auth defined for this operation
var (
noAuth bool
auths []map[string]struct{}
)
if operation.Security != nil {
if len(*operation.Security) == 0 {
noAuth = true
}
for _, req := range *operation.Security {
current := map[string]struct{}{}
for name := range req {
current[name] = struct{}{}
}
if len(current) > 0 {
auths = append(auths, current)
}
}
}
// Use the global security if it was not overridden for this operation
if !noAuth && len(auths) == 0 {
auths = append(auths, globalSecurity...)
}
// For each set of auths, turn them into SecurityInfos, and drop ones that contain unsupported types.
outer:
for _, auth := range auths {
var current []SecurityInfo
for name := range auth {
if scheme, ok := t.Components.SecuritySchemes[name]; ok {
if !slices.Contains(supportedSecurityTypes, scheme.Value.Type) {
// There is an unsupported type in this auth, so move on to the next one.
continue outer
}
current = append(current, SecurityInfo{
Type: scheme.Value.Type,
Name: name,
In: scheme.Value.In,
Scheme: scheme.Value.Scheme,
APIKeyName: scheme.Value.Name,
})
}
}
if len(current) > 0 {
info.SecurityInfos = append(info.SecurityInfos, current)
}
}
argumentsJSON, err := json.MarshalIndent(arguments, "", " ")
if err != nil {
return "", OperationInfo{}, false, err
}
return string(argumentsJSON), info, true, nil
}
}
}
return "", OperationInfo{}, false, nil
}
func parseServer(server *openapi3.Server) (string, error) {
s := server.URL
for name, variable := range server.Variables {
if variable == nil {
continue
}
if variable.Default != "" {
s = strings.Replace(s, "{"+name+"}", variable.Default, 1)
} else if len(variable.Enum) > 0 {
s = strings.Replace(s, "{"+name+"}", variable.Enum[0], 1)
}
}
if !strings.HasPrefix(s, "http") {
return "", fmt.Errorf("invalid server URL: %s (must use HTTP or HTTPS; relative URLs not supported)", s)
}
return s, nil
}
func removeRefs(r *openapi3.SchemaRef) {
if r == nil {
return
}
r.Ref = ""
r.Value.Discriminator = nil // Discriminators are not very useful and can junk up the schema.
for i := range r.Value.OneOf {
removeRefs(r.Value.OneOf[i])
}
for i := range r.Value.AnyOf {
removeRefs(r.Value.AnyOf[i])
}
for i := range r.Value.AllOf {
removeRefs(r.Value.AllOf[i])
}
removeRefs(r.Value.Not)
removeRefs(r.Value.Items)
for i := range r.Value.Properties {
removeRefs(r.Value.Properties[i])
}
}