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>
214 lines
6.2 KiB
Go
214 lines
6.2 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
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"iter"
|
|
"slices"
|
|
"sync"
|
|
|
|
"github.com/modelcontextprotocol/go-sdk/internal/jsonrpc2"
|
|
"github.com/modelcontextprotocol/go-sdk/internal/protocol"
|
|
)
|
|
|
|
// A Server is an instance of an MCP server.
|
|
//
|
|
// Servers expose server-side MCP features, which can serve one or more MCP
|
|
// sessions by using [Server.Start] or [Server.Run].
|
|
type Server struct {
|
|
name string
|
|
version string
|
|
opts ServerOptions
|
|
|
|
mu sync.Mutex
|
|
tools []*Tool
|
|
clients []*ClientConnection
|
|
}
|
|
|
|
// ServerOptions is used to configure behavior of the server.
|
|
type ServerOptions struct {
|
|
Instructions string
|
|
}
|
|
|
|
// NewServer creates a new MCP server. The resulting server has no features:
|
|
// add features using [Server.AddTools]. (TODO: support more features).
|
|
//
|
|
// The server can be connected to one or more MCP clients using [Server.Start]
|
|
// or [Server.Run].
|
|
//
|
|
// If non-nil, the provided options is used to configure the server.
|
|
func NewServer(name, version string, opts *ServerOptions) *Server {
|
|
if opts == nil {
|
|
opts = new(ServerOptions)
|
|
}
|
|
return &Server{
|
|
name: name,
|
|
version: version,
|
|
opts: *opts,
|
|
}
|
|
}
|
|
|
|
// AddTools adds the given tools to the server.
|
|
//
|
|
// TODO(rfindley): notify connected clients of any changes.
|
|
func (s *Server) AddTools(tools ...*Tool) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
s.tools = append(s.tools, tools...)
|
|
}
|
|
|
|
// Clients returns an iterator that yields the current set of client
|
|
// connections.
|
|
func (s *Server) Clients() iter.Seq[*ClientConnection] {
|
|
s.mu.Lock()
|
|
clients := slices.Clone(s.clients)
|
|
s.mu.Unlock()
|
|
return slices.Values(clients)
|
|
}
|
|
|
|
func (s *Server) listTools(_ context.Context, _ *ClientConnection, params *protocol.ListToolsParams) (*protocol.ListToolsResult, error) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
|
|
res := new(protocol.ListToolsResult)
|
|
for _, t := range s.tools {
|
|
res.Tools = append(res.Tools, t.Definition)
|
|
}
|
|
return res, nil
|
|
}
|
|
|
|
func (s *Server) callTool(ctx context.Context, _ *ClientConnection, params *protocol.CallToolParams) (*protocol.CallToolResult, error) {
|
|
s.mu.Lock()
|
|
var tool *Tool
|
|
if i := slices.IndexFunc(s.tools, func(t *Tool) bool {
|
|
return t.Definition.Name == params.Name
|
|
}); i >= 0 {
|
|
tool = s.tools[i]
|
|
}
|
|
s.mu.Unlock()
|
|
|
|
if tool == nil {
|
|
return nil, fmt.Errorf("%s: unknown tool %q", jsonrpc2.ErrInvalidParams, params.Name)
|
|
}
|
|
return tool.Handler(ctx, params.Arguments)
|
|
}
|
|
|
|
// Run runs the server over the given transport, which must be persistent.
|
|
//
|
|
// Run blocks until the client terminates the connection.
|
|
func (s *Server) Run(ctx context.Context, t Transport, opts *ConnectionOptions) error {
|
|
cc, err := s.Connect(ctx, t, opts)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return cc.Wait()
|
|
}
|
|
|
|
// bind implements the binder[*ClientConnection] interface, so that Servers can
|
|
// be connected using [connect].
|
|
func (s *Server) bind(conn *jsonrpc2.Connection) *ClientConnection {
|
|
cc := &ClientConnection{conn: conn, server: s}
|
|
s.mu.Lock()
|
|
s.clients = append(s.clients, cc)
|
|
s.mu.Unlock()
|
|
return cc
|
|
}
|
|
|
|
// disconnect implements the binder[*ClientConnection] interface, so that
|
|
// Servers can be connected using [connect].
|
|
func (s *Server) disconnect(cc *ClientConnection) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
s.clients = slices.DeleteFunc(s.clients, func(cc2 *ClientConnection) bool {
|
|
return cc2 == cc
|
|
})
|
|
}
|
|
|
|
// Connect connects the MCP server over the given transport and starts handling
|
|
// messages.
|
|
//
|
|
// It returns a connection object that may be used to terminate the connection
|
|
// (with [Connection.Close]), or await client termination (with
|
|
// [Connection.Wait]).
|
|
func (s *Server) Connect(ctx context.Context, t Transport, opts *ConnectionOptions) (*ClientConnection, error) {
|
|
return connect(ctx, t, opts, s)
|
|
}
|
|
|
|
// A ClientConnection is a connection with an MCP client.
|
|
//
|
|
// It handles messages from the client, and can be used to send messages to the
|
|
// client. Create a connection by calling [Server.Connect].
|
|
type ClientConnection struct {
|
|
server *Server
|
|
conn *jsonrpc2.Connection
|
|
|
|
mu sync.Mutex
|
|
initializeParams *protocol.InitializeParams // set once initialize has been received
|
|
}
|
|
|
|
func (cc *ClientConnection) handle(ctx context.Context, req *jsonrpc2.Request) (any, error) {
|
|
// TODO: embed the incoming request ID in the ClientContext (or, more likely,
|
|
// a wrapper around it), so that we can correlate responses and notifications
|
|
// to the handler; this is required for the new session-based transport.
|
|
|
|
switch req.Method {
|
|
case "initialize":
|
|
return dispatch(ctx, cc, req, cc.initialize)
|
|
|
|
case "tools/list":
|
|
return dispatch(ctx, cc, req, cc.server.listTools)
|
|
|
|
case "tools/call":
|
|
return dispatch(ctx, cc, req, cc.server.callTool)
|
|
|
|
case "notifications/initialized":
|
|
}
|
|
return nil, jsonrpc2.ErrNotHandled
|
|
}
|
|
|
|
func (cc *ClientConnection) initialize(ctx context.Context, _ *ClientConnection, params *protocol.InitializeParams) (*protocol.InitializeResult, error) {
|
|
cc.mu.Lock()
|
|
cc.initializeParams = params
|
|
cc.mu.Unlock()
|
|
|
|
return &protocol.InitializeResult{
|
|
// TODO(rfindley): support multiple protocol versions.
|
|
ProtocolVersion: "2024-11-05",
|
|
Capabilities: protocol.ServerCapabilities{
|
|
Tools: &protocol.ToolCapabilities{
|
|
ListChanged: true,
|
|
},
|
|
},
|
|
Instructions: cc.server.opts.Instructions,
|
|
ServerInfo: protocol.Implementation{
|
|
Name: cc.server.name,
|
|
Version: cc.server.version,
|
|
},
|
|
}, nil
|
|
}
|
|
|
|
// Close performs a graceful close of the connection, preventing new requests
|
|
// from being handled, and waiting for ongoing requests to return. Close then
|
|
// terminates the connection.
|
|
func (cc *ClientConnection) Close() error {
|
|
return cc.conn.Close()
|
|
}
|
|
|
|
// Wait waits for the connection to be closed by the client.
|
|
func (cc *ClientConnection) Wait() error {
|
|
return cc.conn.Wait()
|
|
}
|
|
|
|
func dispatch[TParams, TResult any](ctx context.Context, conn *ClientConnection, req *jsonrpc2.Request, f func(context.Context, *ClientConnection, TParams) (TResult, error)) (TResult, error) {
|
|
var params TParams
|
|
if err := json.Unmarshal(req.Params, ¶ms); err != nil {
|
|
var zero TResult
|
|
return zero, err
|
|
}
|
|
return f(ctx, conn, params)
|
|
}
|