claude-agent-sdk-python icon indicating copy to clipboard operation
claude-agent-sdk-python copied to clipboard

When the SDK serves as a server agent for multiple users, session confusion and concatenation issues arise due to different sessions for different users

Open RomanLuo523 opened this issue 9 months ago • 2 comments

When the SDK serves as a server agent for multiple users, session confusion and concatenation issues arise due to different sessions for different users

RomanLuo523 avatar Mar 04 '26 06:03 RomanLuo523

I looked into how session isolation works in the SDK and I believe the issue stems from the fact that the CLI subprocess determines session identity based on the working directory (cwd) and an auto-generated or reused session ID, with session files stored under ~/.claude/projects/<sanitized-cwd>/<session_id>.jsonl. When multiple users share the same server process, there are two vectors for session confusion:

  1. Shared session ID via --continue or --resume: If the SDK is used with continue_conversation=True, the CLI resumes the most recent session in that cwd, which in a multi-user server means one user could resume another user's session.

  2. Shared ~/.claude directory: All CLI subprocess instances write to the same ~/.claude/projects/ tree. Without per-user isolation of the Claude home directory, session files from different users can collide if they share the same cwd.

Proposed fix (two layers):

Layer 1 - Per-user session directory isolation: Set the CLAUDE_CONFIG_DIR environment variable (or equivalent) to a unique per-user path before spawning the subprocess. This can be done in SubprocessCLITransport.connect() by injecting it into process_env. The SDK could accept a config_dir option in ClaudeAgentOptions, or the caller could pass it via the existing env dict:

options = ClaudeAgentOptions(
    env={"CLAUDE_CONFIG_DIR": f"/tmp/claude-sessions/{user_id}"}
)

Layer 2 - Document the multi-tenant pattern: Even with directory isolation, ClaudeSDKClient instances should not be shared across users. Each user request should get its own ClaudeSDKClient with its own subprocess. The SDK docs should explicitly call out this pattern for server deployments.

If the CLI does not currently support CLAUDE_CONFIG_DIR, an alternative would be to set unique cwd values per user to force distinct session directories, though that is a less clean solution.

Would this approach work? Happy to submit a PR if so.

weiguangli-io avatar Mar 09 '26 02:03 weiguangli-io

This appears to be a duplicate of #560, which covers the same underlying issue: ClaudeSDKClient does not isolate context across different session_id values in a single long-lived client. Both issues describe session confusion when the SDK is used as a server agent for multiple users.

Closing in favor of #560 — please follow that issue for updates.

qing-ant avatar Mar 24 '26 06:03 qing-ant