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]). If opts.State is non-nil, it is the initial state for
(ctx context.Context, t Transport, opts *ServerSessionOptions)
| 1018 | // |
| 1019 | // If opts.State is non-nil, it is the initial state for the server. |
| 1020 | func (s *Server) Connect(ctx context.Context, t Transport, opts *ServerSessionOptions) (*ServerSession, error) { |
| 1021 | var state *ServerSessionState |
| 1022 | var onClose func() |
| 1023 | if opts != nil { |
| 1024 | state = opts.State |
| 1025 | onClose = opts.onClose |
| 1026 | } |
| 1027 | |
| 1028 | s.opts.Logger.Info("server connecting") |
| 1029 | ss, err := connect(ctx, t, s, state, onClose, s.opts.Logger) |
| 1030 | if err != nil { |
| 1031 | s.opts.Logger.Error("server connect error", "error", err) |
| 1032 | return nil, err |
| 1033 | } |
| 1034 | |
| 1035 | // Start keepalive before returning the session to avoid race conditions with Close. |
| 1036 | // This is safe because the spec allows sending pings before initialization (see ServerSession.handle for details). |
| 1037 | if s.opts.KeepAlive > 0 { |
| 1038 | ss.startKeepalive(ss.server.opts.KeepAlive) |
| 1039 | } |
| 1040 | |
| 1041 | return ss, nil |
| 1042 | } |
| 1043 | |
| 1044 | // TODO: (nit) move all ServerSession methods below the ServerSession declaration. |
| 1045 | func (ss *ServerSession) initialized(ctx context.Context, params *InitializedParams) (Result, error) { |