-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathprocess.go
93 lines (79 loc) · 2 KB
/
process.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
package mcp
import (
"context"
"encoding/json"
)
type empty struct{}
func noop[T any](method func(ctx context.Context, req *Request[T])) func(context.Context, *Request[T]) (*Response[empty], error) {
return func(ctx context.Context, req *Request[T]) (*Response[empty], error) {
method(ctx, req)
return NewResponse(&empty{}), nil
}
}
func process[T, V any](ctx context.Context, cfg *base, msg *Message, method func(ctx context.Context, req *Request[T]) (*Response[V], error)) error {
var interceptor Interceptor
if len(cfg.interceptors) > 0 {
interceptor = newStack(cfg.interceptors)
} else {
interceptor = UnaryInterceptorFunc(
func(next UnaryFunc) UnaryFunc {
return UnaryFunc(func(ctx context.Context, request AnyRequest) (AnyResponse, error) {
return next(ctx, request)
})
},
)
}
var params T
if msg.Params != nil && len(*msg.Params) > 0 {
if err := json.Unmarshal(*msg.Params, ¶ms); err != nil {
return err
}
}
req := NewRequest(¶ms)
if msg.ID != nil {
req.id = msg.ID.String()
}
req.method = *msg.Method
inner := UnaryFunc(func(ctx context.Context, request AnyRequest) (AnyResponse, error) {
req := request.(*Request[T])
resp, rerr := method(ctx, req)
if rerr != nil {
return nil, rerr
}
resp.id = req.id
return resp, nil
})
rr, err := interceptor.WrapUnary(inner)(ctx, req)
// If the incoming message has no ID, we don't need to send a response
if msg.ID == nil {
return nil
}
if err != nil {
return cfg.stream.Send(&Message{
ID: msg.ID,
JsonRPC: msg.JsonRPC,
Error: &ErrorDetail{
Code: 9,
Message: err.Error(),
},
})
}
resp := rr.(*Response[V])
rawresult, err := json.Marshal(resp.Result)
if err != nil {
return cfg.stream.Send(&Message{
ID: msg.ID,
JsonRPC: msg.JsonRPC,
Error: &ErrorDetail{
Code: 9,
Message: err.Error(),
},
})
}
rawmsg := json.RawMessage(rawresult)
return cfg.stream.Send(&Message{
ID: msg.ID,
JsonRPC: msg.JsonRPC,
Result: &rawmsg,
})
}