Skip to content

feat(client): add session persistence and restoration support #426

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,61 @@ func (c *Client) Initialize(
return &result, nil
}

// ExportState exports the current client state for later resumption.
//
// The exported state includes:
// - Initialization status
// - Current request ID counter
// - Client and server capabilities
// - Transport session ID (for HTTP transports)
func (c *Client) ExportState() *mcp.ClientState {
return &mcp.ClientState{
Initialized: c.initialized,
RequestID: c.requestID.Load(),
ClientCapabilities: c.clientCapabilities,
ServerCapabilities: c.serverCapabilities,
SessionID: c.getTransportSessionID(),
}
}

func (c *Client) getTransportSessionID() string {
if t, ok := c.transport.(*transport.StreamableHTTP); ok {
return t.GetSessionId()
}
return ""
}

func (c *Client) setTransportSessionID(sessionID string) {
if t, ok := c.transport.(*transport.StreamableHTTP); ok && sessionID != "" {
t.SetSessionId(sessionID)
}
}

// ImportState restores the client state from a previously exported state.
//
// The client transport must be started before calling this method.
func (c *Client) ImportState(ctx context.Context, state *mcp.ClientState) error {
if state == nil {
return fmt.Errorf("state cannot be nil")
}

if c.transport == nil {
return fmt.Errorf("transport is not initialized")
}

if state.Initialized && state.RequestID < 0 {
return fmt.Errorf("invalid state: initialized client must have non-negative request ID")
}

c.initialized = state.Initialized
c.requestID.Store(state.RequestID)
c.clientCapabilities = state.ClientCapabilities
c.serverCapabilities = state.ServerCapabilities
c.setTransportSessionID(state.SessionID)

return nil
}

func (c *Client) Ping(ctx context.Context) error {
_, err := c.sendRequest(ctx, "ping", nil)
return err
Expand Down
79 changes: 79 additions & 0 deletions client/client_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package client

import (
"context"
"testing"

"github.com/mark3labs/mcp-go/mcp"
"github.com/mark3labs/mcp-go/server"
)

func TestStateRestoration(t *testing.T) {
mcpServer := server.NewMCPServer(
"test-server",
"1.0.0",
server.WithToolCapabilities(true),
)

// First client lifecycle
client1, err := NewInProcessClient(mcpServer)
if err != nil {
t.Fatalf("Failed to create first client: %v", err)
}

ctx := context.Background()

if err := client1.Start(ctx); err != nil {
t.Fatalf("Failed to start first client: %v", err)
}

initRequest := mcp.InitializeRequest{}
initRequest.Params.ProtocolVersion = mcp.LATEST_PROTOCOL_VERSION
initRequest.Params.ClientInfo = mcp.Implementation{
Name: "test-client",
Version: "1.0.0",
}

if _, err := client1.Initialize(ctx, initRequest); err != nil {
t.Fatalf("Failed to initialize first client: %v", err)
}

if err := client1.Ping(ctx); err != nil {
t.Fatalf("Ping on first client failed: %v", err)
}

exportedState := client1.ExportState()

if err := client1.Close(); err != nil {
t.Fatalf("Failed to close first client: %v", err)
}

// Second client lifecycle (state restoration)
client2, err := NewInProcessClient(mcpServer)
if err != nil {
t.Fatalf("Failed to create second client: %v", err)
}
defer client2.Close()

if err := client2.Start(ctx); err != nil {
t.Fatalf("Failed to start second client: %v", err)
}

if err := client2.ImportState(ctx, exportedState); err != nil {
t.Fatalf("Failed to import state into second client: %v", err)
}

if err := client2.Ping(ctx); err != nil {
t.Fatalf("Ping on restored client failed: %v", err)
}

restoredState := client2.ExportState()

if !restoredState.Initialized {
t.Errorf("Expected restored client to be initialized")
}

if restoredState.RequestID <= exportedState.RequestID {
t.Errorf("Expected request ID to increase after restoration; before=%d, after=%d", exportedState.RequestID, restoredState.RequestID)
}
}
5 changes: 5 additions & 0 deletions client/transport/streamable_http.go
Original file line number Diff line number Diff line change
Expand Up @@ -513,3 +513,8 @@ func (c *StreamableHTTP) GetOAuthHandler() *OAuthHandler {
func (c *StreamableHTTP) IsOAuthEnabled() bool {
return c.oauthHandler != nil
}

// SetSessionId sets the session ID for the transport
func (c *StreamableHTTP) SetSessionId(sessionID string) {
c.sessionID.Store(sessionID)
}
18 changes: 18 additions & 0 deletions mcp/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -1042,3 +1042,21 @@ type ServerResult any
type Named interface {
GetName() string
}

// ClientState represents the resumable state of an MCP client
type ClientState struct {
// Initialized indicates whether the client has been initialized
Initialized bool `json:"initialized"`

// RequestID is the last used request ID
RequestID int64 `json:"requestId"`

// ClientCapabilities represents the client's capabilities
ClientCapabilities ClientCapabilities `json:"clientCapabilities"`

// ServerCapabilities represents the server's capabilities
ServerCapabilities ServerCapabilities `json:"serverCapabilities"`

// SessionID is the session ID from the transport (if any)
SessionID string `json:"sessionId,omitempty"`
}
35 changes: 35 additions & 0 deletions www/docs/pages/clients/basics.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,41 @@ func (mc *ManagedClient) Close() error {
}
```

### Persisting & Restoring Client State

MCP-Go lets you snapshot a running client and resume it later — even in a new
process — with `ExportState()` and `ImportState()`.

```go
// Save state before shutting down
state := client.ExportState()
if err := client.Close(); err != nil {
log.Printf("close failed: %v", err)
}

// Later, or in another process
restoredClient, _ := client.NewStreamableHttpClient(baseURL)
_ = restoredClient.Start(ctx) // transport must be running
if err := restoredClient.ImportState(ctx, state); err != nil {
log.Fatal(err)
}

// Continue exactly where you left off
if err := restoredClient.Ping(ctx); err != nil {
log.Fatal(err)
}
```

`ExportState()` captures:

* initialization status
* last JSON-RPC request ID (so IDs continue monotonically)
* negotiated client / server capabilities
* HTTP session ID (for StreamableHTTP transports)

`ImportState()` re-hydrates those values. After a successful call the
restored client can immediately issue normal requests without re-initializing.

## Error Handling

Proper error handling is essential for robust client applications.
Expand Down