Prerequisite: an agent saved in the Registry. See Create an agent or the Agent Playground. For the conceptual overview and a full walkthrough, see SDK overview.
Install and connect
Running agents uses the gateway SDK, not thetruefoundry client.
truefoundry-gateway-sdk from npm. Both languages import AgentSessionClient — Python from truefoundry_gateway_sdk.agents, TypeScript from truefoundry-gateway-sdk/agents. Set TFY_GATEWAY_URL and TFY_API_KEY as above. Every example below comes in both languages.
Create a session
A session is the conversation context for a saved agent — one customer working through one issue. It persists across many turns; persistsession.id to resume later.
Open a session
A Session is the conversation context for a saved agent. Create one by name withcreate_session / createSession.
List sessions for an agent
List the existing sessions for a saved agent withlist_sessions / listSessions. It iterates newest-first and auto-paginates. Use it to resume an earlier conversation — each Session exposes its id (persist or reuse it to continue).
Create a turn
A turn is one request/response cycle. Send input, the agent runs until it finishes or pauses, then the stream closes. Create another turn on the same session to continue — turns chain automatically.Create and stream a turn
Create a turn withsession.prepare_turn() / session.prepareTurn(), then call turn.execute(stream=True) / turn.execute({ stream: true }) to start it and stream its events as they arrive. The first event is always turn.created (carrying the turn_id); the stream closes with turn.done.
When the stream runs to completion, read the terminal state from turn.state. If you break out of the loop early, call turn.refresh() first.
To continue the conversation, create another Turn on the same session. Turns within a session are chained automatically, so each Turn sees the history of the ones before it.
Creating a new Turn in a session automatically cancels any other Turn that is still running in that session.
List turns
List the turns in a session withlistTurns() / list_turns(). Each turn exposes its input, and state holds the current lifecycle state.
list_turns() always returns turns in descending order (newest-first).Non-streaming turn
If you don’t need live events, callturn.execute(stream=False) and read the returned terminal state (or read turn.state after consuming a full stream).
Attach images or files to a turn
AUserMessage’s content can be a plain string or a list of content parts. Use content parts to send text alongside one or more file uploads (images, PDFs, and other documents). Each file is passed as a data URI of the form data:<mime>;base64,<payload>.
Whether an attached file is understood depends on the agent’s model. Send images only to a vision-capable model; document handling (for example, PDFs) likewise depends on model and agent configuration.
Non-image files such as PDFs require the sandbox to be enabled on the agent - the harness uses it to process the document.
Cancel a turn
To stop the currently running turn, callsession.cancel() on the session. Cancelling aborts any in-flight model request, waits for running MCP tool calls to finish, and force-stops any sandbox the turn provisioned. Cancellation is idempotent. You can continue by creating a new turn, which chains on the cancelled turn’s history.
Handle MCP outbound auth
When the agent needs to call a tool on an MCP server that requires a separate outbound authentication, it emits anmcp.auth_required event and the Turn ends. The event lists each server that needs authentication along with an auth_url. Depending on how the server is configured, this may be an OAuth flow or an API-key entry - see MCP authentication scenarios for details. Send the user to that URL to complete authentication, then resume by creating a new Turn.
When the previous Turn ended with
mcp.auth_required, passing a UserMessage in the resuming Turn is not allowed.Handle tool approvals
When a tool call is configured to require human approval, the agent emits atool.approval_required event and the turn ends. Each event carries a thread_id and the tool_calls awaiting a decision — a single turn can emit more than one (for example, when parallel threads each call a gated tool), so collect all of them. Resume by creating a new turn with one UserToolApprovalEvent per pending tool call — allow it, or deny it with an optional reason.
Each pending ToolCallRef carries the source_event_id of the model.message that emitted the tool call. Keep the same id-keyed event index you build while streaming, then look up events[source_event_id] to read the tool’s name and arguments — no separate bookkeeping required.
Answer agent questions
When the agent needs input it cannot safely assume, it can ask the user a structured question via the built-in client-sideask_user_question tool. Since the tool runs on your side, the agent emits a tool.response_required event and the turn ends. The pending tool call’s arguments carry the question and its options. Collect the user’s answer and resume by creating a new turn with one UserToolResponseEvent per pending tool call.
Each pending ToolCallRef carries the source_event_id of the model.message that emitted the tool call. Keep the same id-keyed event index you build while streaming, then look up events[source_event_id] to read the tool’s name and arguments — no separate bookkeeping required.
Subscribe to events
Every turn emits a stream of events over SSE. The stream opens withturn.created and closes with turn.done. See the Turn events reference for every event type.
Handling Event Delta while streaming
Most events in a Turn are complete on their own - a single payload you can use directly. Some updates are streamed instead: the base event arrives first, followed by a series of Event Deltas - incremental fragments that you merge into the base. All deltas for one update share the base event’sid, while sequence_number increases across the base and all its deltas.
id, keep an id-keyed index of assembled events: store each non-delta event under its id, and merge each delta into the base with the same id. The id is unique per message, so deltas from concurrently streaming threads (the main agent and any sub-agents) always merge into the right base.
Both languages ship
is_event_delta and merge_event_delta from truefoundry_gateway_sdk.agents (Python) and truefoundry-gateway-sdk/agents (TypeScript).Event Deltas appear only while streaming. When you list turn events via the events API, the deltas are already merged into a single assembled event.
ModelMessageEvent followed by ModelMessageDeltaEvent deltas that carry incremental text and tool-call chunks. Merge the deltas into the base as they arrive — read the base’s growing content for a live typing effect.
Resume streaming
When you lose the originalexecute(stream=True) stream (for example, after a page reload), call client.get_session() and session.get_turn(), then check turn.state. If it is still running, reconnect with turn.stream(after_sequence_number=...) and keep merging; if it has already finished, rebuild the index from turn.list_events() instead.
When resuming a running turn, pass after_sequence_number to continue after a known point; the stream closes when the turn reaches a terminal state. Either way, merge into the same id-keyed index of assembled events, so base events and their deltas keep merging seamlessly across the reconnect.
In Python, track last_sequence_number from each event’s sequence_number field while streaming (use data.sequence_number when present). The stream wrapper may leave TurnStreamData.sequence_number as None.
Handle threads
A single Turn stream interleaves events from the root agent and any sub-agents that run in parallel. Every event carries athread_id:
"main"— the root agent.- A unique ID — a sub-agent thread.
thread.createdandthread.donemark sub-agent thread lifecycle; they are not emitted for the main thread. null— a turn-level event, not tied to any thread:turn.createdandturn.done(first and last on the stream),sandbox.created, andmcp.auth_required.
main and the sub-agent), and the run pauses for an approval before a second turn resumes it. Solid arrows are turn inputs you send; dashed arrows are SSE events streamed back to your client.
Listing Events
Fetch the full event log of a finished turn withturn.list_events(). It yields the turn’s events in order and auto-paginates. Pass order="asc" (default, oldest-first) or order="desc" to control the direction.
Unlike turn.execute(stream=True) and turn.stream(), turn.list_events() returns already-merged events: each model message arrives as a single assembled ModelMessageEvent, never as a base plus deltas. There is nothing to merge — you can use each event directly.
For example, a model message that stream() delivers as a base event followed by deltas:
turn.list_events() as one fully-merged event:
turn.list_events() is only available for turns that have completed. A running turn has no stored event log yet — use turn.execute(stream=True) or turn.stream() for live delivery instead.