1package transport
2
3import (
4 "context"
5 "encoding/json"
6
7 "github.com/mark3labs/mcp-go/mcp"
8)
9
10// HTTPHeaderFunc is a function that extracts header entries from the given context
11// and returns them as key-value pairs. This is typically used to add context values
12// as HTTP headers in outgoing requests.
13type HTTPHeaderFunc func(context.Context) map[string]string
14
15// Interface for the transport layer.
16type Interface interface {
17 // Start the connection. Start should only be called once.
18 Start(ctx context.Context) error
19
20 // SendRequest sends a json RPC request and returns the response synchronously.
21 SendRequest(ctx context.Context, request JSONRPCRequest) (*JSONRPCResponse, error)
22
23 // SendNotification sends a json RPC Notification to the server.
24 SendNotification(ctx context.Context, notification mcp.JSONRPCNotification) error
25
26 // SetNotificationHandler sets the handler for notifications.
27 // Any notification before the handler is set will be discarded.
28 SetNotificationHandler(handler func(notification mcp.JSONRPCNotification))
29
30 // Close the connection.
31 Close() error
32
33 // GetSessionId returns the session ID of the transport.
34 GetSessionId() string
35}
36
37// RequestHandler defines a function that handles incoming requests from the server.
38type RequestHandler func(ctx context.Context, request JSONRPCRequest) (*JSONRPCResponse, error)
39
40// BidirectionalInterface extends Interface to support incoming requests from the server.
41// This is used for features like sampling where the server can send requests to the client.
42type BidirectionalInterface interface {
43 Interface
44
45 // SetRequestHandler sets the handler for incoming requests from the server.
46 // The handler should process the request and return a response.
47 SetRequestHandler(handler RequestHandler)
48}
49
50type JSONRPCRequest struct {
51 JSONRPC string `json:"jsonrpc"`
52 ID mcp.RequestId `json:"id"`
53 Method string `json:"method"`
54 Params any `json:"params,omitempty"`
55}
56
57type JSONRPCResponse struct {
58 JSONRPC string `json:"jsonrpc"`
59 ID mcp.RequestId `json:"id"`
60 Result json.RawMessage `json:"result,omitempty"`
61 Error *struct {
62 Code int `json:"code"`
63 Message string `json:"message"`
64 Data json.RawMessage `json:"data"`
65 } `json:"error,omitempty"`
66}