Skip to content

Shared state across client sessions not preserved in servers_counter_sse example due to per-session instantiation #257

@fatslow

Description

@fatslow

Summary

While testing the servers_counter_sse example, I noticed that multiple clients see different counter values when calling get_value, even though the counter appears to be global.

Steps to Reproduce

  1. Run cargo run --example servers_counter_sse from root directory.
  2. Connect two different MCP clients (in my case MCP Inspector and n8n MPC Client node).
  3. Call increment or decrement from one client.
  4. Then call get_value from the other client.

Observed Behavior

Each client sees a different counter value, indicating that each has its own isolated instance of the Counter service. The counter state is not shared across sessions.

Root Cause

The line in examples/servers/src/counter_sse.rs uses Counter::new as a factory:

      let ct = sse_server.with_service(Counter::new);

By changing this to

    let shared_counter = Counter::new();
    let ct = sse_server.with_service(move || shared_counter.clone());

…all clients now correctly share the same counter state. Calling increment from one client is reflected when calling get_value from another.

Suggestion

Either update the example to explicitly share the state, or clarify in the example comments that state is per-session by default and how to share it properly.

Let me know if this behavior is intended or if the example should be updated accordingly. I’m happy to submit a PR if helpful.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions