go-sdk/mcp/sse_example_test.go
Robert Findley 204b59483b
mcp,design: revert 'content' back to an interface type (#29)
After some experience with the flattened version of Content, we see that
it can easily lead to incorrect usage and is a harder API to read.
Therefore, this CL changes back to a design similar to what we had prior
to https://go.dev/cl/672415, though opting to promote content
unmarshalling to the protocol types that use it, which leads to an
overall simpler api.
2025-06-25 13:09:05 -04:00

56 lines
1.4 KiB
Go

// 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"
"fmt"
"log"
"net/http"
"net/http/httptest"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
type AddParams struct {
X, Y int
}
func Add(ctx context.Context, cc *mcp.ServerSession, params *mcp.CallToolParamsFor[AddParams]) (*mcp.CallToolResultFor[any], error) {
return &mcp.CallToolResultFor[any]{
Content: []mcp.Content{
&mcp.TextContent{Text: fmt.Sprintf("%d", params.Arguments.X+params.Arguments.Y)},
},
}, nil
}
func ExampleSSEHandler() {
server := mcp.NewServer("adder", "v0.0.1", nil)
server.AddTools(mcp.NewServerTool("add", "add two numbers", Add))
handler := mcp.NewSSEHandler(func(*http.Request) *mcp.Server { return server })
httpServer := httptest.NewServer(handler)
defer httpServer.Close()
ctx := context.Background()
transport := mcp.NewSSEClientTransport(httpServer.URL, nil)
client := mcp.NewClient("test", "v1.0.0", nil)
cs, err := client.Connect(ctx, transport)
if err != nil {
log.Fatal(err)
}
defer cs.Close()
res, err := cs.CallTool(ctx, &mcp.CallToolParams{
Name: "add",
Arguments: map[string]any{"x": 1, "y": 2},
})
if err != nil {
log.Fatal(err)
}
fmt.Println(res.Content[0].(*mcp.TextContent).Text)
// Output: 3
}