ClaudeCode.Session (ClaudeCode v0.36.3)
View SourcePublic API for interacting with Claude Code sessions.
This module provides functions for managing session lifecycle, runtime
configuration, MCP server management, and introspection. For the basic
"getting started" API, see ClaudeCode.
Session Lifecycle
{:ok, session} = ClaudeCode.Session.start_link(api_key: "sk-ant-...")
ClaudeCode.Session.stream(session, "What is 5 + 3?")
|> Enum.each(&IO.inspect/1)
ClaudeCode.Session.stop(session)Runtime Configuration
:ok = ClaudeCode.Session.set_model(session, "claude-sonnet-4-5-20250929")
:ok = ClaudeCode.Session.set_permission_mode(session, :accept_edits)MCP Server Management
{:ok, servers} = ClaudeCode.Session.mcp_status(session)
:ok = ClaudeCode.Session.mcp_reconnect(session, "my-server")Introspection
{:ok, info} = ClaudeCode.Session.server_info(session)
{:ok, models} = ClaudeCode.Session.supported_models(session)
Summary
Functions
Returns account information from the initialization response.
Checks if a session is alive.
Clears the current session ID to start a fresh conversation.
Executes an arbitrary function call on the adapter's node.
Reads conversation messages for the current session.
Returns the health status of the session's adapter.
Interrupts the current generation.
Lists sessions with rich metadata from the adapter's node.
Reconnects a disconnected or failed MCP server.
Queries MCP server connection status.
Enables or disables an MCP server.
Rewinds tracked files to the state at a specific user message checkpoint.
Gets server initialization info cached from the control handshake.
Gets the current session ID for conversation continuity.
Replaces the set of dynamically managed MCP servers.
Changes the model mid-conversation.
Changes the permission mode mid-conversation.
Starts a new Claude Code session.
Stops a Claude Code session.
Stops a running task.
Sends a query to a session and returns a stream of messages.
Returns the list of available subagents from the initialization response.
Returns the list of available commands from the initialization response.
Returns the list of available models from the initialization response.
Types
Functions
@spec account_info(session()) :: {:ok, ClaudeCode.Session.AccountInfo.t() | nil} | {:error, term()}
Returns account information from the initialization response.
Examples
{:ok, account} = ClaudeCode.Session.account_info(session)
IO.puts(account.email)
Checks if a session is alive.
Examples
true = ClaudeCode.Session.alive?(session)
@spec clear(session()) :: :ok
Clears the current session ID to start a fresh conversation.
This will cause the next query to start a new conversation context rather than continuing the existing one. Useful when you want to reset the conversation history.
Examples
:ok = ClaudeCode.Session.clear(session)
# Next stream will start fresh
ClaudeCode.Session.stream(session, "Hello!")
|> Enum.each(&IO.inspect/1)
Executes an arbitrary function call on the adapter's node.
Runs apply(module, function, args) on whatever node the adapter lives on.
For local adapters (Port), this is equivalent to a direct apply. For
distributed adapters (Node), this dispatches via :rpc.call.
Examples
# Read a file on the adapter's node
{:ok, contents} = ClaudeCode.Session.execute(session, File, :read, ["/workspace/config.json"])
# List directory on the adapter's node
{:ok, files} = ClaudeCode.Session.execute(session, File, :ls, ["/workspace"])
# Run a custom module function
result = ClaudeCode.Session.execute(session, MyApp.Sandbox, :cleanup, [workspace_id])
@spec get_messages( session(), keyword() ) :: {:ok, [ClaudeCode.History.SessionMessage.t()]} | {:error, term()}
Reads conversation messages for the current session.
Routes through the session server so History reads execute on the
correct node (local for Port, remote for Node adapter). Returns
{:ok, []} if no session ID has been captured yet (no queries made).
For local-only access by session ID string, use
ClaudeCode.History.get_messages/2 directly.
Options
:project_path- Project directory to find the session in:limit- Maximum number of messages to return:offset- Number of messages to skip from the start (default: 0):claude_dir- Override the Claude directory (default:~/.claude)
Examples
{:ok, session} = ClaudeCode.start_link()
ClaudeCode.Session.stream(session, "Hello!") |> Stream.run()
{:ok, messages} = ClaudeCode.Session.get_messages(session)
# With pagination
{:ok, page} = ClaudeCode.Session.get_messages(session, limit: 10, offset: 5)See ClaudeCode.History.get_messages/2 for more details.
@spec health(session()) :: ClaudeCode.Adapter.health()
Returns the health status of the session's adapter.
Examples
:healthy = ClaudeCode.Session.health(session)
{:unhealthy, :port_dead} = ClaudeCode.Session.health(session)
Interrupts the current generation.
Sends an interrupt signal to the CLI to stop the current generation. This is a fire-and-forget operation — the CLI will stop generating and emit a result message.
Examples
:ok = ClaudeCode.Session.interrupt(session)
@spec list_sessions( session(), keyword() ) :: {:ok, [ClaudeCode.History.SessionInfo.t()]}
Lists sessions with rich metadata from the adapter's node.
Automatically injects :project_path from the session's :cwd option
if not provided. When :project_path is set, returns sessions for that
project directory. When omitted, returns sessions across all projects.
For local-only access, use ClaudeCode.History.list_sessions/1 directly.
Options
:project_path- Project directory to list sessions for (default: session cwd):limit- Maximum number of sessions to return:include_worktrees- Scan git worktrees (default:true):claude_dir- Override~/.claude(for testing)
Examples
{:ok, sessions} = ClaudeCode.Session.list_sessions(session)
{:ok, recent} = ClaudeCode.Session.list_sessions(session, limit: 10)See ClaudeCode.History.list_sessions/1 for more details.
Reconnects a disconnected or failed MCP server.
Examples
:ok = ClaudeCode.Session.mcp_reconnect(session, "my-server")
@spec mcp_status(session()) :: {:ok, [ClaudeCode.MCP.Status.t()]} | {:error, term()}
Queries MCP server connection status.
Examples
{:ok, servers} = ClaudeCode.Session.mcp_status(session)
Enum.each(servers, &IO.puts(&1.name))
Enables or disables an MCP server.
Examples
:ok = ClaudeCode.Session.mcp_toggle(session, "my-server", false)
@spec rewind_files(session(), String.t(), keyword()) :: {:ok, ClaudeCode.CLI.Control.Types.rewind_files_result()} | {:error, term()}
Rewinds tracked files to the state at a specific user message checkpoint.
Options
:dry_run- Whentrue, preview changes without applying them (default:false)
Examples
{:ok, _} = ClaudeCode.Session.rewind_files(session, "user-msg-uuid-123")
# Preview changes without applying
{:ok, preview} = ClaudeCode.Session.rewind_files(session, "user-msg-uuid-123", dry_run: true)
@spec server_info(session()) :: {:ok, ClaudeCode.CLI.Control.Types.initialize_response() | nil} | {:error, term()}
Gets server initialization info cached from the control handshake.
Examples
{:ok, info} = ClaudeCode.Session.server_info(session)
Gets the current session ID for conversation continuity.
Returns the session ID that Claude CLI is using to maintain conversation context. This ID is automatically captured from CLI responses and used for subsequent queries to continue the conversation.
You can use this session ID with the :resume option when starting a
new session to continue the conversation later, or with :fork_session
to create a branch.
Examples
session_id = ClaudeCode.Session.session_id(session)
# => "abc123-session-id"
# For a new session with no queries yet
nil = ClaudeCode.Session.session_id(session)
# Resume later
{:ok, new_session} = ClaudeCode.start_link(resume: session_id)
# Or fork the conversation
{:ok, forked} = ClaudeCode.start_link(resume: session_id, fork_session: true)
@spec set_mcp_servers(session(), map()) :: {:ok, ClaudeCode.CLI.Control.Types.set_servers_result()} | {:error, term()}
Replaces the set of dynamically managed MCP servers.
Examples
{:ok, _} = ClaudeCode.Session.set_mcp_servers(session, %{"tools" => %{"type" => "stdio", "command" => "npx"}})
Changes the model mid-conversation.
Examples
:ok = ClaudeCode.Session.set_model(session, "claude-sonnet-4-5-20250929")
Changes the permission mode mid-conversation.
Examples
:ok = ClaudeCode.Session.set_permission_mode(session, :bypass_permissions)
@spec start_link(keyword()) :: GenServer.on_start()
Starts a new Claude Code session.
See ClaudeCode.start_link/1 for full documentation and examples.
@spec stop(session()) :: :ok
Stops a Claude Code session.
This closes the CLI subprocess and cleans up resources.
Examples
:ok = ClaudeCode.Session.stop(session)
Stops a running task.
A task_notification with status 'stopped' will be emitted.
Examples
:ok = ClaudeCode.Session.stop_task(session, "task-id-123")
@spec stream(session(), String.t(), keyword()) :: Enumerable.t(ClaudeCode.Message.t())
Sends a query to a session and returns a stream of messages.
See ClaudeCode.stream/3 for full documentation and examples.
@spec supported_agents(session()) :: {:ok, [ClaudeCode.Session.AgentInfo.t()]} | {:error, term()}
Returns the list of available subagents from the initialization response.
Examples
{:ok, agents} = ClaudeCode.Session.supported_agents(session)
@spec supported_commands(session()) :: {:ok, [ClaudeCode.Session.SlashCommand.t()]} | {:error, term()}
Returns the list of available commands from the initialization response.
Examples
{:ok, commands} = ClaudeCode.Session.supported_commands(session)
Enum.each(commands, &IO.puts(&1.name))
@spec supported_models(session()) :: {:ok, [ClaudeCode.Model.Info.t()]} | {:error, term()}
Returns the list of available models from the initialization response.
Examples
{:ok, models} = ClaudeCode.Session.supported_models(session)
Enum.each(models, &IO.puts(&1.display_name))