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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
|
package main
import (
"bufio"
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"sort"
"strings"
"sync"
"time"
)
// This file implements a minimal MCP (Model Context Protocol) client, enough
// to drive `gopls mcp` as a subprocess and expose its go_* tools to the model.
//
// It is hand-rolled rather than built on github.com/modelcontextprotocol/go-sdk
// for the same reason the Gemini calls are hand-rolled (see DESIGN.md): the SDK
// abstracts over transports and schema drafts we do not use, and pulls in four
// dependencies to send three JSON-RPC methods. We need exactly `initialize`,
// `tools/list` and `tools/call`, all over newline-delimited JSON on stdio.
//
// The server is a child process, so its lifetime is the REPL's lifetime; tools
// are discovered once at startup rather than re-listed per turn.
// mcpCallTimeout bounds a single tools/call. gopls has to load and type-check
// the workspace on its first call, which is far slower than the ones after it,
// so this is generous rather than snappy.
const mcpCallTimeout = 120 * time.Second
// mcpClient is a JSON-RPC 2.0 client speaking MCP to a subprocess over stdio.
type mcpClient struct {
name string
cmd *exec.Cmd
stdin io.WriteCloser
out *bufio.Reader
// mu serialises request/response pairs. MCP allows pipelining by id, but
// the agent loop calls tools one at a time, and a mutex keeps the reader
// from having to demultiplex.
mu sync.Mutex
nextID int
tools []mcpTool
// errMu guards the fields below, which are written by the stderr-draining
// goroutine and read from the main goroutine after the handshake.
errMu sync.Mutex
// loadErr is the first workspace-load complaint the server made on stderr,
// empty if it never made one.
loadErr string
// rawSchemas are the tools' input schemas byte for byte, by tool name.
rawSchemas map[string]json.RawMessage
// prefix is what Anthropic sees in front of each tool's name; see
// registerMCPTools.
prefix string
}
// mcpTool is the subset of an MCP tool definition we care about.
type mcpTool struct {
Name string `json:"name"`
Description string `json:"description"`
InputSchema map[string]any `json:"inputSchema"`
}
// mcpToolRaw is the same definition with the schema as the server wrote it,
// key order included, for Anthropic, which receives it unmodified.
type mcpToolRaw struct {
Name string `json:"name"`
InputSchema json.RawMessage `json:"inputSchema"`
}
type jsonrpcRequest struct {
JSONRPC string `json:"jsonrpc"`
ID *int `json:"id,omitempty"`
Method string `json:"method"`
Params any `json:"params,omitempty"`
}
type jsonrpcResponse struct {
JSONRPC string `json:"jsonrpc"`
ID *int `json:"id,omitempty"`
Method string `json:"method,omitempty"`
Result json.RawMessage `json:"result,omitempty"`
Error *jsonrpcError `json:"error,omitempty"`
}
type jsonrpcError struct {
Code int `json:"code"`
Message string `json:"message"`
}
func (e *jsonrpcError) Error() string {
return fmt.Sprintf("jsonrpc error %d: %s", e.Code, e.Message)
}
// mcpContent is one item of a tools/call result.
type mcpContent struct {
Type string `json:"type"`
Text string `json:"text"`
}
type callToolResult struct {
Content []mcpContent `json:"content"`
IsError bool `json:"isError"`
}
// startMCP launches an MCP server subprocess, performs the initialize
// handshake and lists its tools.
//
// dir becomes the child's working directory, which is how gopls decides which
// workspace to load; it must be the module or go.work root, not an arbitrary
// path.
func startMCP(name string, argv []string, dir string) (*mcpClient, error) {
if len(argv) == 0 {
return nil, fmt.Errorf("empty command")
}
cmd := exec.Command(argv[0], argv[1:]...)
cmd.Dir = dir
stdin, err := cmd.StdinPipe()
if err != nil {
return nil, fmt.Errorf("stdin pipe: %w", err)
}
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, fmt.Errorf("stdout pipe: %w", err)
}
// stderr is always drained, not just under -v: it carries the only signal
// that the workspace failed to load, and that failure is otherwise
// invisible (see watchStderr).
stderr, err := cmd.StderrPipe()
if err != nil {
return nil, fmt.Errorf("stderr pipe: %w", err)
}
if err := cmd.Start(); err != nil {
return nil, fmt.Errorf("start %s: %w", argv[0], err)
}
c := &mcpClient{
prefix: name + "_",
name: name,
cmd: cmd,
stdin: stdin,
out: bufio.NewReader(stdout),
}
go c.watchStderr(stderr)
if err := c.handshake(); err != nil {
c.Close()
return nil, err
}
if err := c.loadTools(); err != nil {
c.Close()
return nil, err
}
return c, nil
}
// workspaceLoadMarkers are the substrings gopls prints on stderr when
// go/packages fails to load the workspace. The common cause is the `go` it
// finds on PATH being older than the go.work directive; gopls forces
// GOTOOLCHAIN=local for that subprocess, so the toolchain switcher cannot
// rescue it.
//
// This is matched on log text, which is fragile, but there is no structured
// alternative: the failure is not reported over the protocol at all. The
// symptom it prevents is worth the fragility -- see checkWorkspace.
var workspaceLoadMarkers = []string{
"initial workspace load failed",
"go/packages.Load",
}
// watchStderr drains the server's stderr for the process' lifetime, forwarding
// it under -v and latching the first workspace-load complaint either way.
//
// Draining matters even when nothing is looking: a server whose stderr fills
// the pipe buffer blocks on write, which would deadlock the session.
func (c *mcpClient) watchStderr(r io.Reader) {
scanner := bufio.NewScanner(r)
scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024)
for scanner.Scan() {
line := scanner.Text()
if verbose {
fmt.Fprintf(os.Stderr, "[mcp:%s] %s\n", c.name, line)
}
for _, marker := range workspaceLoadMarkers {
if !strings.Contains(line, marker) {
continue
}
c.errMu.Lock()
if c.loadErr == "" {
c.loadErr = strings.TrimSpace(line)
}
c.errMu.Unlock()
break
}
}
}
// workspaceLoadError returns the server's first workspace-load complaint, or
// "" if it never made one.
func (c *mcpClient) workspaceLoadError() string {
c.errMu.Lock()
defer c.errMu.Unlock()
return c.loadErr
}
// checkWorkspace reports why the server's Go workspace is unusable, or "" if
// it is fine.
//
// This exists because the failure is silent in the worst possible way: when
// go/packages fails to load, go_search and go_symbol_references answer "No
// symbols found" rather than erroring, which the model cannot distinguish from
// the symbol genuinely not existing. It will then report that working code
// does not exist.
//
// Note that go_workspace is *not* a usable health check on its own: it reads
// go.work textually and cheerfully lists every module even when nothing
// type-checked. It is only consulted here for the case it does detect, namely
// not being in a Go workspace at all.
func (c *mcpClient) checkWorkspace(ctx context.Context) string {
if msg := c.workspaceLoadError(); msg != "" {
return msg
}
if !c.has("go_workspace") {
return ""
}
out := c.callTool(ctx, "go_workspace", map[string]any{})
if strings.Contains(out, "not a Go workspace") {
return strings.TrimSpace(out)
}
// The load can also fail after go_workspace has answered, since gopls
// loads packages asynchronously; re-check the latch.
return c.workspaceLoadError()
}
// handshake performs initialize followed by the initialized notification.
//
// The server's `instructions` field is deliberately dropped. gopls returns
// ~5.5KB of prescriptive workflow prose ("you MUST call go_diagnostics after
// every edit") written for an agent with a full read/write/edit toolset. hans
// has one file-reading tool and a 109-byte system prompt, so the instructions
// would be fifty times the prompt they modify and would mandate steps hans
// cannot take. The tool descriptions are self-describing enough.
func (c *mcpClient) handshake() error {
params := map[string]any{
"protocolVersion": "2025-06-18",
"capabilities": map[string]any{},
"clientInfo": map[string]any{
"name": "hans",
"version": "0",
},
}
if _, err := c.request("initialize", params); err != nil {
return fmt.Errorf("initialize: %w", err)
}
if err := c.notify("notifications/initialized", nil); err != nil {
return fmt.Errorf("initialized notification: %w", err)
}
return nil
}
func (c *mcpClient) loadTools() error {
raw, err := c.request("tools/list", map[string]any{})
if err != nil {
return fmt.Errorf("tools/list: %w", err)
}
var res struct {
Tools []mcpTool `json:"tools"`
}
if err := json.Unmarshal(raw, &res); err != nil {
return fmt.Errorf("decode tools/list: %w", err)
}
var rawRes struct {
Tools []mcpToolRaw `json:"tools"`
}
json.Unmarshal(raw, &rawRes)
c.rawSchemas = map[string]json.RawMessage{}
for _, t := range rawRes.Tools {
var compact bytes.Buffer
if json.Compact(&compact, t.InputSchema) == nil {
c.rawSchemas[t.Name] = compact.Bytes()
}
}
// Stable order keeps the tool declarations (and therefore the cached
// prompt prefix) byte-identical across runs.
sort.Slice(res.Tools, func(i, j int) bool { return res.Tools[i].Name < res.Tools[j].Name })
c.tools = res.Tools
return nil
}
// request sends a JSON-RPC request and waits for the response with a matching
// id, skipping any notifications or unrelated messages that arrive first.
func (c *mcpClient) request(method string, params any) (json.RawMessage, error) {
c.mu.Lock()
defer c.mu.Unlock()
c.nextID++
id := c.nextID
if err := c.write(jsonrpcRequest{JSONRPC: "2.0", ID: &id, Method: method, Params: params}); err != nil {
return nil, err
}
for {
line, err := c.out.ReadBytes('\n')
if err != nil {
return nil, fmt.Errorf("read response: %w", err)
}
if len(strings.TrimSpace(string(line))) == 0 {
continue
}
var resp jsonrpcResponse
if err := json.Unmarshal(line, &resp); err != nil {
return nil, fmt.Errorf("decode response: %w\nraw: %s", err, line)
}
// Server-initiated notifications and requests carry no matching id.
if resp.ID == nil || *resp.ID != id {
if verbose {
fmt.Fprintf(os.Stderr, "[mcp:%s] skipping %s\n", c.name, resp.Method)
}
continue
}
if resp.Error != nil {
return nil, resp.Error
}
return resp.Result, nil
}
}
func (c *mcpClient) notify(method string, params any) error {
return c.write(jsonrpcRequest{JSONRPC: "2.0", Method: method, Params: params})
}
func (c *mcpClient) write(v any) error {
b, err := json.Marshal(v)
if err != nil {
return fmt.Errorf("marshal: %w", err)
}
b = append(b, '\n')
if _, err := c.stdin.Write(b); err != nil {
return fmt.Errorf("write: %w", err)
}
return nil
}
// callTool invokes a tool and flattens its result into the plain string the
// agent loop feeds back to the model.
func (c *mcpClient) callTool(ctx context.Context, name string, args map[string]any) string {
ctx, cancel := context.WithTimeout(ctx, mcpCallTimeout)
defer cancel()
type outcome struct {
raw json.RawMessage
err error
}
ch := make(chan outcome, 1)
go func() {
raw, err := c.request("tools/call", map[string]any{
"name": name,
"arguments": args,
})
ch <- outcome{raw, err}
}()
var res outcome
select {
case res = <-ch:
case <-ctx.Done():
// The in-flight request still holds c.mu, and its response is still
// queued on stdout; simply returning would leave the next call to read
// this one's answer. Killing the server forces that read to fail, which
// releases the mutex and makes every later call fail honestly instead
// of returning mismatched results.
if c.cmd != nil && c.cmd.Process != nil {
c.cmd.Process.Kill()
}
return fmt.Sprintf("error: %s timed out after %s; MCP server killed", name, mcpCallTimeout)
}
if res.err != nil {
return fmt.Sprintf("error: %s", res.err)
}
var out callToolResult
if err := json.Unmarshal(res.raw, &out); err != nil {
return fmt.Sprintf("error: decode result of %s: %s", name, err)
}
var sb strings.Builder
for _, item := range out.Content {
if item.Type == "text" {
sb.WriteString(item.Text)
}
}
text := sb.String()
if out.IsError {
return fmt.Sprintf("error: %s", text)
}
if text == "" {
return fmt.Sprintf("(%s returned no content)", name)
}
return text
}
func (c *mcpClient) Close() error {
if c.stdin != nil {
c.stdin.Close()
}
if c.cmd != nil && c.cmd.Process != nil {
// Closing stdin is the protocol's shutdown signal; give it a moment
// before insisting.
done := make(chan struct{})
go func() { c.cmd.Wait(); close(done) }()
select {
case <-done:
case <-time.After(2 * time.Second):
c.cmd.Process.Kill()
}
}
return nil
}
// has reports whether this client provides the named tool.
// unprefixed maps a name as Anthropic saw it back to the server's own.
func (c *mcpClient) unprefixed(name string) (string, bool) {
if c.prefix != "" && strings.HasPrefix(name, c.prefix) && c.has(strings.TrimPrefix(name, c.prefix)) {
return strings.TrimPrefix(name, c.prefix), true
}
return "", false
}
func (c *mcpClient) has(name string) bool {
for _, t := range c.tools {
if t.Name == name {
return true
}
}
return false
}
// --- Schema translation ---
// sanitizeSchema rewrites a JSON Schema (2020-12, as emitted by gopls) into
// the OpenAPI 3.0 subset Gemini accepts for functionDeclaration.parameters.
//
// This is not cosmetic. Gemini rejects unknown keys outright, and every gopls
// tool carries an `additionalProperties` key, so passing the schemas through
// untouched fails the request with an opaque 400 rather than misbehaving
// locally.
//
// Two shapes have to be repaired rather than merely filtered:
//
// - `"type": ["null", "array"]`. JSON Schema allows a list of types; Gemini's
// `type` is a single enum and rejects the list outright ("Proto field is
// not repeating, cannot start list"). gopls 0.22 emits this for every
// optional array parameter, so it is the common case, not an edge case.
// - `"additionalProperties": {"not": {}}` in 0.20, plain `false` in 0.22.
// Dropped either way.
func sanitizeSchema(in map[string]any) map[string]any {
// Keys Gemini understands. Anything else is dropped rather than mapped:
// silently approximating a constraint is worse than not stating it, since
// the model would treat the result as authoritative.
allowed := map[string]bool{
"type": true,
"format": true,
"description": true,
"nullable": true,
"enum": true,
"items": true,
"properties": true,
"required": true,
}
out := make(map[string]any, len(in))
for k, v := range in {
if !allowed[k] {
continue
}
switch k {
case "properties":
props, ok := v.(map[string]any)
if !ok {
continue
}
cleaned := make(map[string]any, len(props))
for name, sub := range props {
if subMap, ok := sub.(map[string]any); ok {
cleaned[name] = sanitizeSchema(subMap)
}
}
if len(cleaned) > 0 {
out[k] = cleaned
}
case "items":
if subMap, ok := v.(map[string]any); ok {
out[k] = sanitizeSchema(subMap)
}
case "type":
t, nullable := singleType(v)
if t == "" {
continue
}
out[k] = t
// A ["null", T] union is JSON Schema's way of saying "optional";
// Gemini spells that as a separate boolean, so preserve the
// meaning instead of dropping it with the list.
if nullable {
out["nullable"] = true
}
default:
out[k] = v
}
}
return out
}
// singleType collapses a JSON Schema `type` into Gemini's single-valued form,
// reporting whether "null" was among the alternatives.
//
// Only one non-null type is expected in practice; if a schema offers a genuine
// choice (say ["string","number"]) there is no faithful translation, so the
// first is taken and the rest dropped rather than inventing a union.
func singleType(v any) (typ string, nullable bool) {
switch t := v.(type) {
case string:
return t, false
case []any:
for _, item := range t {
s, ok := item.(string)
if !ok {
continue
}
if s == "null" {
nullable = true
continue
}
if typ == "" {
typ = s
}
}
return typ, nullable
default:
return "", false
}
}
// geminiParameters converts a tool's input schema for the streamGenerateContent
// and Interactions APIs, returning nil when the tool takes no arguments.
//
// The nil case matters: gopls declares go_workspace as an object with no
// properties, and Gemini rejects a parameters object that declares none.
func geminiParameters(schema map[string]any) map[string]any {
if schema == nil {
return nil
}
clean := sanitizeSchema(schema)
props, _ := clean["properties"].(map[string]any)
if len(props) == 0 {
return nil
}
return clean
}
// registerMCPTools appends the client's tools to every API's declaration
// list, so any agent loop can call them. Anthropic takes JSON Schema as gopls
// writes it, so it gets the schema unmodified; it requires one, so a tool with
// none is declared as taking an empty object.
func registerMCPTools(c *mcpClient) {
if c == nil || len(c.tools) == 0 {
return
}
for _, t := range c.tools {
params := geminiParameters(t.InputSchema)
tools[0].FunctionDeclarations = append(tools[0].FunctionDeclarations, functionDeclaration{
Name: t.Name,
Description: t.Description,
Parameters: params,
})
interactionTools = append(interactionTools, interactionTool{
Type: "function",
Name: t.Name,
Description: t.Description,
Parameters: params,
})
// As OpenCode declares an MCP tool: named <server>_<tool> with
// anything but [a-zA-Z0-9_-] replaced by "_", and the schema as the
// server wrote it, with type, properties and additionalProperties
// set as {...schema, type: "object", properties: schema.properties
// ?? {}, additionalProperties: false} would set them.
anthropicMCPTools = append(anthropicMCPTools, anthropicTool{
Name: opencodeToolName(c.prefix + t.Name),
Description: t.Description,
InputSchema: opencodeMCPSchema(c.rawSchemas[t.Name]),
})
}
}
func opencodeToolName(s string) string {
return strings.Map(func(r rune) rune {
switch {
case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9', r == '_', r == '-':
return r
}
return '_'
}, s)
}
// opencodeMCPSchema applies OpenCode's spread to a schema without reordering
// it: keys already present keep their place and take the new value, new ones
// go at the end, as in a JavaScript object spread.
func opencodeMCPSchema(raw json.RawMessage) json.RawMessage {
f, err := parseFields(raw)
if err != nil {
f = nil
}
props := f.get("properties")
if props == nil || string(props) == "null" {
props = json.RawMessage("{}")
}
f = f.set("type", "object")
f = f.set("properties", props)
f = f.set("additionalProperties", false)
return f.encode()
}
// probe: cache invalidation test
|