internal/mcp: implement HTTP SSE transport
Add support for SSE transport, as defined by version 2024-11-05 and 2025-03-26 of the MCP spec. In order to achieve this, the jsonrpc2 stream must be abstracted so that we can implement it across multiple HTTP requests. This required some refactoring of the jsonrpc2_v2 package, so that we can avoid the Dialer/Binder interfaces and construct the Connection directly from its constituent primitives. Change-Id: Id627b5b5a474d92f2c613cfad904d14611e7c768 Reviewed-on: https://go-review.googlesource.com/c/tools/+/667475 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
1204b93a85
commit
ef446f82d7
1 changed files with 771 additions and 223 deletions
|
|
@ -6,16 +6,15 @@ package main
|
|||
|
||||
import (
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
)
|
||||
|
||||
type Optional[T any] struct {
|
||||
present bool
|
||||
value T
|
||||
}
|
||||
var httpAddr = flag.String("http", "", "if set, use SSE HTTP at this address, instead of stdin/stdout")
|
||||
|
||||
type SayHiParams struct {
|
||||
Name string `json:"name" mcp:"the name to say hi to"`
|
||||
|
|
@ -28,11 +27,20 @@ func SayHi(ctx context.Context, params *SayHiParams) ([]mcp.Content, error) {
|
|||
}
|
||||
|
||||
func main() {
|
||||
flag.Parse()
|
||||
|
||||
server := mcp.NewServer("greeter", "v0.0.1", nil)
|
||||
server.AddTools(mcp.MakeTool("greet", "say hi", SayHi))
|
||||
|
||||
opts := &mcp.ConnectionOptions{Logger: os.Stderr}
|
||||
if err := server.Run(context.Background(), mcp.NewStdIOTransport(), opts); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Server failed: %v", err)
|
||||
if *httpAddr != "" {
|
||||
handler := mcp.NewSSEHandler(func() *mcp.Server {
|
||||
return server
|
||||
})
|
||||
http.ListenAndServe(*httpAddr, handler)
|
||||
} else {
|
||||
opts := &mcp.ConnectionOptions{Logger: os.Stderr}
|
||||
if err := server.Run(context.Background(), mcp.NewStdIOTransport(), opts); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Server failed: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue