-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodemode.go
More file actions
264 lines (215 loc) · 4.67 KB
/
Copy pathcodemode.go
File metadata and controls
264 lines (215 loc) · 4.67 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
// path: codemode/codemode_mcp.go
package codemode
import (
"bytes"
"context"
"fmt"
"reflect"
"sync"
"time"
"github.com/mark3labs/mcp-go/mcp"
"github.com/traefik/yaegi/interp"
"github.com/traefik/yaegi/stdlib"
)
const CodeModeToolName = "codemode.run_code"
var (
minimalStdlibOnce sync.Once
minimalStdlibCache map[string]map[string]reflect.Value
)
func getMinimalStdlib() map[string]map[string]reflect.Value {
minimalStdlibOnce.Do(func() {
minimalStdlibCache = map[string]map[string]reflect.Value{}
neededPackages := []string{
"context/context",
"fmt/fmt",
"reflect/reflect",
}
for _, pkg := range neededPackages {
if symbols, ok := stdlib.Symbols[pkg]; ok {
minimalStdlibCache[pkg] = symbols
}
}
})
return minimalStdlibCache
}
type CodeModeArgs struct {
Code string `json:"code"`
Timeout int `json:"timeout"`
}
type CodeModeResult struct {
Value any `json:"value"`
Stdout string `json:"stdout"`
Stderr string `json:"stderr"`
}
type MCPClient interface {
ListTools(
ctx context.Context,
request mcp.ListToolsRequest,
) (*mcp.ListToolsResult, error)
CallTool(
ctx context.Context,
request mcp.CallToolRequest,
) (*mcp.CallToolResult, error)
}
type CodeModeMCP struct {
client MCPClient
}
func NewCodeModeMCP(client MCPClient) *CodeModeMCP {
return &CodeModeMCP{
client: client,
}
}
func newInterpreter() (*interp.Interpreter, *bytes.Buffer, *bytes.Buffer) {
var stdout, stderr bytes.Buffer
i := interp.New(interp.Options{
Stdout: &stdout,
Stderr: &stderr,
})
return i, &stdout, &stderr
}
func injectHelpers(
i *interp.Interpreter,
mcpClient MCPClient,
) error {
if err := i.Use(getMinimalStdlib()); err != nil {
return err
}
exports := interp.Exports{
"codemode_helpers/codemode_helpers": map[string]reflect.Value{
"CallTool": reflect.ValueOf(
func(
name string,
args map[string]any,
) (any, error) {
res, err := mcpClient.CallTool(
context.Background(),
mcp.CallToolRequest{
Params: mcp.CallToolParams{
Name: name,
Arguments: args,
},
},
)
if err != nil {
return nil, err
}
if res.IsError {
var errMsg string
for _, c := range res.Content {
if tc, ok := c.(mcp.TextContent); ok {
errMsg += tc.Text
} else if tc, ok := c.(*mcp.TextContent); ok {
errMsg += tc.Text
}
}
if errMsg == "" {
errMsg = "tool returned an error result without message"
}
return nil, fmt.Errorf("tool error: %s", errMsg)
}
if res.StructuredContent != nil {
return res.StructuredContent, nil
}
var out string
for _, c := range res.Content {
if tc, ok := c.(mcp.TextContent); ok {
out += tc.Text
} else if tc, ok := c.(*mcp.TextContent); ok {
out += tc.Text
}
}
return out, nil
},
),
"ListTools": reflect.ValueOf(
func() ([]mcp.Tool, error) {
res, err := mcpClient.ListTools(
context.Background(),
mcp.ListToolsRequest{},
)
if err != nil {
return nil, err
}
return res.Tools, nil
},
),
"Errorf": reflect.ValueOf(fmt.Errorf),
"Sprintf": reflect.ValueOf(fmt.Sprintf),
},
}
return i.Use(exports)
}
func (c *CodeModeMCP) Execute(
ctx context.Context,
args CodeModeArgs,
) (CodeModeResult, error) {
timeoutMs := args.Timeout
if timeoutMs <= 0 {
timeoutMs = 30000
}
ctx, cancel := context.WithTimeout(
ctx,
time.Duration(timeoutMs)*time.Millisecond,
)
defer cancel()
i, stdout, stderr := newInterpreter()
if err := injectHelpers(i, c.client); err != nil {
return CodeModeResult{}, err
}
wrapped := wrapIntoProgram(
preprocessUserCode(args.Code),
)
type evalResult struct {
val reflect.Value
err error
}
done := make(chan evalResult, 1)
go func() {
defer func() {
if r := recover(); r != nil {
done <- evalResult{
err: fmt.Errorf(
"interpreter panic: %v",
r,
),
}
}
}()
if _, err := i.Eval(wrapped); err != nil {
done <- evalResult{
err: fmt.Errorf(
"compilation failed: %w",
err,
),
}
return
}
v, err := i.Eval(`main.run()`)
done <- evalResult{
val: v,
err: err,
}
}()
select {
case <-ctx.Done():
return CodeModeResult{
Stdout: stdout.String(),
Stderr: stderr.String(),
}, fmt.Errorf(
"execution timed out after %dms",
timeoutMs,
)
case res := <-done:
if res.err != nil {
return CodeModeResult{
Stdout: stdout.String(),
Stderr: stderr.String(),
}, res.err
}
return CodeModeResult{
Value: res.val.Interface(),
Stdout: stdout.String(),
Stderr: stderr.String(),
}, nil
}
}