MCPcopy Create free account
hub / github.com/modelcontextprotocol/go-sdk / TestSynchronousNotifications

Function TestSynchronousNotifications

mcp/mcp_test.go:1957–2022  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

1955}
1956
1957func TestSynchronousNotifications(t *testing.T) {
1958 synctest.Test(t, func(t *testing.T) {
1959 var toolsChanged atomic.Int32
1960 clientOpts := &ClientOptions{
1961 ToolListChangedHandler: func(ctx context.Context, req *ToolListChangedRequest) {
1962 toolsChanged.Add(1)
1963 },
1964 CreateMessageHandler: func(ctx context.Context, req *CreateMessageRequest) (*CreateMessageResult, error) {
1965 // See the comment after "from server" below.
1966 if n := toolsChanged.Load(); n != 1 {
1967 return nil, fmt.Errorf("got %d tools-changed notification, wanted 1", n)
1968 }
1969 // TODO(rfindley): investigate the error returned from this test if
1970 // CreateMessageResult is new(CreateMessageResult): it's a mysterious
1971 // unmarshalling error that we should improve.
1972 return &CreateMessageResult{Content: &TextContent{}}, nil
1973 },
1974 }
1975 client := NewClient(testImpl, clientOpts)
1976
1977 var rootsChanged atomic.Bool
1978 serverOpts := &ServerOptions{
1979 RootsListChangedHandler: func(_ context.Context, req *RootsListChangedRequest) {
1980 rootsChanged.Store(true)
1981 },
1982 }
1983 server := NewServer(testImpl, serverOpts)
1984 addTool := func(s *Server) {
1985 AddTool(s, &Tool{Name: "tool"}, func(ctx context.Context, req *CallToolRequest, args any) (*CallToolResult, any, error) {
1986 if !rootsChanged.Load() {
1987 return nil, nil, fmt.Errorf("didn't get root change notification")
1988 }
1989 return new(CallToolResult), nil, nil
1990 })
1991 }
1992 cs, ss, cleanup := basicClientServerConnection(t, client, server, addTool)
1993 defer cleanup()
1994
1995 t.Log("from client")
1996 {
1997 client.AddRoots(&Root{Name: "myroot", URI: "file://foo"})
1998 res, err := cs.CallTool(context.Background(), &CallToolParams{Name: "tool"})
1999 if err != nil {
2000 t.Fatalf("CallTool failed: %v", err)
2001 }
2002 if res.IsError {
2003 t.Errorf("tool error: %v", res.Content[0].(*TextContent).Text)
2004 }
2005 }
2006
2007 t.Log("from server")
2008 {
2009 // Despite all this tool-changed activity, we expect only one notification.
2010 for range 10 {
2011 server.RemoveTools("tool")
2012 addTool(server)
2013 }
2014

Callers

nothing calls this directly

Calls 9

AddRootsMethod · 0.95
RemoveToolsMethod · 0.95
NewClientFunction · 0.85
NewServerFunction · 0.85
AddToolFunction · 0.85
LogMethod · 0.80
CallToolMethod · 0.80
CreateMessageMethod · 0.80

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…