internal/mcp: add a command transport for connecting to a sidecar
Add a missing CommandTransport that communicates with a sidecar process over newline-delimited stdin/stdout, the counterpart to the existing StdIOTransport. Add a test using the usual TestMain trick. Change-Id: I170ba78faf6b6d7fca7da1af11bf92e919b11ed5 Reviewed-on: https://go-review.googlesource.com/c/tools/+/668895 LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com> Reviewed-by: Jonathan Amsterdam <jba@google.com>
This commit is contained in:
parent
860a55afbc
commit
56ed3872f3
1 changed files with 175 additions and 4 deletions
67
mcp/cmd_test.go
Normal file
67
mcp/cmd_test.go
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
// Copyright 2025 The Go MCP SDK Authors. All rights reserved.
|
||||
// Use of this source code is governed by an MIT-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package mcp_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"os"
|
||||
"os/exec"
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
)
|
||||
|
||||
const runAsServer = "_MCP_RUN_AS_SERVER"
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
if os.Getenv(runAsServer) != "" {
|
||||
os.Unsetenv(runAsServer)
|
||||
runServer()
|
||||
return
|
||||
}
|
||||
os.Exit(m.Run())
|
||||
}
|
||||
|
||||
func runServer() {
|
||||
ctx := context.Background()
|
||||
|
||||
server := mcp.NewServer("greeter", "v0.0.1", nil)
|
||||
server.AddTools(mcp.MakeTool("greet", "say hi", SayHi))
|
||||
|
||||
if err := server.Run(ctx, mcp.NewStdIOTransport(), nil); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCmdTransport(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
exe, err := os.Executable()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cmd := exec.Command(exe)
|
||||
cmd.Env = append(os.Environ(), runAsServer+"=true")
|
||||
|
||||
client := mcp.NewClient("client", "v0.0.1", nil)
|
||||
serverConn, err := client.Connect(ctx, mcp.NewCommandTransport(cmd), nil)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
got, err := serverConn.CallTool(ctx, "greet", SayHiParams{Name: "user"})
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
want := []mcp.Content{mcp.TextContent{Text: "Hi user"}}
|
||||
if diff := cmp.Diff(want, got); diff != "" {
|
||||
t.Errorf("greet returned unexpected content (-want +got):\n%s", diff)
|
||||
}
|
||||
if err := serverConn.Close(); err != nil {
|
||||
t.Fatalf("closing server: %v", err)
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue