Debian Codegraph @

debian/go/src/github.com/modelcontextprotocol/go-sdk/mcp/cmd_test.go

raw symbols SCIP
1 // Copyright 2025 The Go MCP SDK Authors. All rights reserved.
2 // Use of this source code is governed by an MIT-style
3 // license that can be found in the LICENSE file.
4
5 package mcp_test
6
7 import (
8 "context"
9 "errors"
10 "log"
11 "os"
12 "os/exec"
13 "os/signal"
14 "runtime"
15 "syscall"
16 "testing"
17 "testing/synctest"
18 "time"
19
20 "github.com/google/go-cmp/cmp"
21 "github.com/modelcontextprotocol/go-sdk/mcp"
22 )
23
24 const runAsServer = "_MCP_RUN_AS_SERVER"
25
26 type SayHiParams struct {
27 Name string `json:"name"`
28 }
29
30 func SayHi(ctx context.Context, req *mcp.CallToolRequest, args SayHiParams) (*mcp.CallToolResult, any, error) {
31 return &mcp.CallToolResult{
32 Content: []mcp.Content{
33 &mcp.TextContent{Text: "Hi " + args.Name},
34 },
35 }, nil, nil
36 }
37
38 func TestMain(m *testing.M) {
39 // If the runAsServer variable is set, execute the relevant serverFunc
40 // instead of running tests (aka the fork and exec trick).
41 if name := os.Getenv(runAsServer); name != "" {
42 run := serverFuncs[name]
43 if run == nil {
44 log.Fatalf("Unknown server %q", name)
45 }
46 os.Unsetenv(runAsServer)
47 run()
48 return
49 }
50 os.Exit(m.Run())
51 }
52
53 // serverFuncs defines server functions that may be run as subprocesses via
54 // [TestMain].
55 var serverFuncs = map[string]func(){
56 "default": runServer,
57 "cancelContext": runCancelContextServer,
58 }
59
60 func runServer() {
61 ctx := context.Background()
62
63 server := mcp.NewServer(testImpl, nil)
64 mcp.AddTool(server, &mcp.Tool{Name: "greet", Description: "say hi"}, SayHi)
65 if err := server.Run(ctx, &mcp.StdioTransport{}); err != nil {
66 log.Fatal(err)
67 }
68 }
69
70 func runCancelContextServer() {
71 ctx, done := signal.NotifyContext(context.Background(), syscall.SIGINT)
72 defer done()
73
74 server := mcp.NewServer(testImpl, nil)
75 if err := server.Run(ctx, &mcp.StdioTransport{}); err != nil {
76 log.Fatal(err)
77 }
78 }
79
80 func TestServerRunContextCancel(t *testing.T) {
81 synctest.Test(t, func(t *testing.T) {
82 server := mcp.NewServer(&mcp.Implementation{Name: "greeter", Version: "v0.0.1"}, nil)
83 mcp.AddTool(server, &mcp.Tool{Name: "greet", Description: "say hi"}, SayHi)
84
85 ctx, cancel := context.WithCancel(context.Background())
86 defer cancel()
87
88 serverTransport, clientTransport := mcp.NewInMemoryTransports()
89
90 // run the server and capture the exit error
91 onServerExit := make(chan error)
92 go func() {
93 onServerExit <- server.Run(ctx, serverTransport)
94 }()
95
96 // send a ping to the server to ensure it's running
97 client := mcp.NewClient(&mcp.Implementation{Name: "client", Version: "v0.0.1"}, nil)
98 session, err := client.Connect(ctx, clientTransport, nil)
99 if err != nil {
100 t.Fatal(err)
101 }
102 t.Cleanup(func() { session.Close() })
103
104 if err := session.Ping(context.Background(), nil); err != nil {
105 t.Fatal(err)
106 }
107
108 // cancel the context to stop the server
109 cancel()
110
111 // wait for the server to exit
112
113 err = <-onServerExit
114 if !errors.Is(err, context.Canceled) {
115 t.Fatalf("server did not exit after context cancellation, got error: %v", err)
116 }
117 })
118 }
119
120 func TestServerInterrupt(t *testing.T) {
121 if runtime.GOOS == "windows" {
122 t.Skip("requires POSIX signals")
123 }
124 requireExec(t)
125
126 t.Log("Starting server command")
127 cmd := createServerCommand(t, "default")
128
129 client := mcp.NewClient(testImpl, nil)
130 t.Log("Connecting to server")
131
132 ctx := context.Background()
133 session, err := client.Connect(ctx, &mcp.CommandTransport{Command: cmd}, nil)
134 if err != nil {
135 t.Fatal(err)
136 }
137
138 t.Log("Send a signal to the server process to terminate it")
139 if err := cmd.Process.Signal(os.Interrupt); err != nil {
140 t.Fatal(err)
141 }
142
143 t.Log("Closing client session so server can exit immediately")
144 session.Close()
145
146 t.Log("Wait for process to terminate after interrupt signal")
147 _, err = cmd.Process.Wait()
148 if err == nil {
149 t.Errorf("unexpected error: %v", err)
150 }
151 }
152
153 func TestStdioContextCancellation(t *testing.T) {
154 if runtime.GOOS == "windows" {
155 t.Skip("requires POSIX signals")
156 }
157 requireExec(t)
158
159 // This test is a variant of TestServerInterrupt reproducing the conditions
160 // of #224, where interrupt failed to shut down the server because reads of
161 // Stdin were not unblocked.
162
163 cmd := createServerCommand(t, "cancelContext")
164 // Creating a stdin pipe causes os.Stdin.Close to not immediately unblock
165 // pending reads.
166 _, _ = cmd.StdinPipe()
167
168 // Just Start the command, rather than connecting to the server, because we
169 // don't want the client connection to indirectly flush stdin through writes.
170 if err := cmd.Start(); err != nil {
171 t.Fatalf("starting command: %v", err)
172 }
173
174 // Sleep to make it more likely that the server is blocked in the read loop.
175 //
176 // This sleep isn't necessary for the test to pass, but *was* necessary for
177 // it to fail, before closing was fixed. Unfortunately, it is too invasive a
178 // change to have the jsonrpc2 package signal across packages when it is
179 // actually blocked in its read loop.
180 time.Sleep(100 * time.Millisecond)
181
182 onExit := make(chan struct{})
183 go func() {
184 cmd.Process.Wait()
185 close(onExit)
186 }()
187
188 if err := cmd.Process.Signal(os.Interrupt); err != nil {
189 t.Fatal(err)
190 }
191
192 select {
193 case <-time.After(5 * time.Second):
194 t.Fatal("server did not exit after SIGINT")
195 case <-onExit:
196 t.Logf("done.")
197 }
198 }
199
200 func TestCmdTransport(t *testing.T) {
201 requireExec(t)
202
203 ctx := t.Context()
204
205 cmd := createServerCommand(t, "default")
206
207 client := mcp.NewClient(&mcp.Implementation{Name: "client", Version: "v0.0.1"}, nil)
208 session, err := client.Connect(ctx, &mcp.CommandTransport{Command: cmd}, nil)
209 if err != nil {
210 t.Fatal(err)
211 }
212 got, err := session.CallTool(ctx, &mcp.CallToolParams{
213 Name: "greet",
214 Arguments: map[string]any{"name": "user"},
215 })
216 if err != nil {
217 t.Fatal(err)
218 }
219 want := &mcp.CallToolResult{
220 Content: []mcp.Content{
221 &mcp.TextContent{Text: "Hi user"},
222 },
223 }
224 if diff := cmp.Diff(want, got, ctrCmpOpts...); diff != "" {
225 t.Errorf("greet returned unexpected content (-want +got):\n%s", diff)
226 }
227 if err := session.Close(); err != nil {
228 t.Fatalf("closing server: %v", err)
229 }
230 }
231
232 // createServerCommand creates a command to fork and exec the test binary as an
233 // MCP server.
234 //
235 // serverName must refer to an entry in the [serverFuncs] map.
236 func createServerCommand(t *testing.T, serverName string) *exec.Cmd {
237 t.Helper()
238
239 exe, err := os.Executable()
240 if err != nil {
241 t.Fatal(err)
242 }
243 cmd := exec.Command(exe)
244 cmd.Env = append(os.Environ(), runAsServer+"="+serverName)
245
246 return cmd
247 }
248
249 func TestCommandTransportTerminateDuration(t *testing.T) {
250 if runtime.GOOS == "windows" {
251 t.Skip("requires POSIX signals")
252 }
253 requireExec(t)
254
255 // Unfortunately, since it does I/O, this test needs to rely on timing (we
256 // can't use synctest). However, we can still decrease the default
257 // termination duration to speed up the test.
258 const defaultDur = 50 * time.Millisecond
259 defer mcp.SetDefaultTerminateDuration(defaultDur)()
260
261 tests := []struct {
262 name string
263 duration time.Duration
264 wantMinDuration time.Duration
265 wantMaxDuration time.Duration
266 }{
267 {
268 name: "default duration (zero)",
269 duration: 0,
270 wantMinDuration: defaultDur,
271 wantMaxDuration: 1 * time.Second, // default + buffer
272 },
273 {
274 name: "below minimum duration",
275 duration: -500 * time.Millisecond,
276 wantMinDuration: defaultDur,
277 wantMaxDuration: 1 * time.Second, // should use default + buffer
278 },
279 {
280 name: "custom valid duration",
281 duration: 200 * time.Millisecond,
282 wantMinDuration: 200 * time.Millisecond,
283 wantMaxDuration: 1 * time.Second, // custom + buffer
284 },
285 }
286
287 for _, tt := range tests {
288 t.Run(tt.name, func(t *testing.T) {
289 ctx := t.Context()
290
291 // Use a command that won't exit when stdin is closed
292 cmd := exec.Command("sleep", "20")
293 transport := &mcp.CommandTransport{
294 Command: cmd,
295 TerminateDuration: tt.duration,
296 }
297
298 conn, err := transport.Connect(ctx)
299 if err != nil {
300 t.Fatal(err)
301 }
302
303 start := time.Now()
304 err = conn.Close()
305 elapsed := time.Since(start)
306
307 if err != nil {
308 var exitErr *exec.ExitError
309 if !errors.As(err, &exitErr) {
310 t.Fatalf("Close() failed with unexpected error: %v", err)
311 }
312 }
313 if elapsed < tt.wantMinDuration {
314 t.Errorf("Close() took %v, expected at least %v", elapsed, tt.wantMinDuration)
315 }
316 if elapsed > tt.wantMaxDuration {
317 t.Errorf("Close() took %v, expected at most %v", elapsed, tt.wantMaxDuration)
318 }
319
320 // Ensure the process was actually terminated
321 if cmd.Process != nil {
322 cmd.Process.Kill()
323 }
324 })
325 }
326 }
327
328 func requireExec(t *testing.T) {
329 t.Helper()
330
331 // Conservatively, limit to major OS where we know that os.Exec is
332 // supported.
333 switch runtime.GOOS {
334 case "darwin", "linux", "windows":
335 default:
336 t.Skip("unsupported OS")
337 }
338 }
339
340 var testImpl = &mcp.Implementation{Name: "test", Version: "v1.0.0"}