Skip to main content
For a guided walkthrough, see SDK overview.

Turn input

Each Turn’s input is a list of one of these types. Resuming a Turn paused by mcp.auth_required needs no input - omit input or pass [].
User messages (UserMessage) cannot be mixed with tool approvals or client-side tool responses in the same input list. UserToolApprovalEvent and UserToolResponseEvent may be mixed together.

UserMessage

Start a new conversation or send the next user message. content is either a plain string or a list of content parts, letting you attach files alongside text.
{ "type": "user.message", "content": "I would like to file a support ticket." }
{
    "type": "user.message",
    "content": [
        { "type": "text", "text": "Please review this document." },
        {
            "type": "file",
            "name": "report.pdf",
            "data": "data:application/pdf;base64,JVBERi0xLjQK..."
        }
    ]
}
FieldTypeRequiredDescription
type"user.message"Yes
contentstring | UserMessageContentItem[]YesThe message text, or a list of content parts (text and files).

UserMessageContentItem

A content part is one of: Text
FieldTypeRequiredDescription
type"text"Yes
textstringYesThe message text.
File
FieldTypeRequiredDescription
type"file"Yes
namestringYesName of the uploaded file.
datastringYesData URI: data:<mime>;base64,<payload>. MIME type is parsed from the URI.

UserToolApprovalEvent

Sent to resume a turn paused by tool.approval_required. One item per pending tool call.
{
    "type": "user.tool_approval",
    "thread_id": "main",
    "tool_call_id": "call_restart_billing",
    "approval": { "status": "allow" }
}
FieldTypeRequiredDescription
type"user.tool_approval"Yes
thread_idstringYesthread_id from the tool.approval_required event.
tool_call_idstringYesID of the tool call being approved or denied.
approvalApprovalAllow | ApprovalDenyYesUse {"status": "allow"} to permit the call, or {"status": "deny", "reason": "..."} to block it. reason is optional.

UserToolResponseEvent

Sent to resume a turn paused by tool.response_required. One item per pending tool call.
{
    "type": "user.tool_response",
    "thread_id": "main",
    "tool_call_id": "call_a1b2",
    "content": "tfy-prod-us (production)"
}
FieldTypeRequiredDescription
type"user.tool_response"Yes
thread_idstringYesthread_id from the tool.response_required event.
tool_call_idstringYesID of the tool call whose result is being supplied.
contentstringYesThe result to return to the agent.

Reference

The signatures below document the low-level generated client (TrueFoundryGatewayclient.agents.sessions.*). For application code, prefer the high-level AgentSessionClient / AgentSessionClient wrapper from truefoundry_gateway_sdk.agents (Python) or truefoundry-gateway-sdk/agents (TypeScript) — same prepare_turn / execute / Turn model as the examples in Use an agent.

Python reference

import os
from truefoundry_gateway_sdk.agents import AgentSessionClient

client = AgentSessionClient(
    base_url=os.environ["TFY_GATEWAY_URL"],
    api_key=os.environ["TFY_API_KEY"],
)
session = client.create_session(agent_name="support-bot")
turn = session.prepare_turn(input=[...])
for data in turn.execute(stream=True):
    print(data.event)
MethodDescription
create_session(agent_name)Create a session
list_sessions(agent_name, ...)List sessions (newest-first pager)
get_session(session_id)Fetch session by id
session.prepare_turn(input=..., previous_turn_id=...)Stage a turn (no HTTP yet)
turn.execute(stream=True|False)Start turn; stream events or wait for terminal state
turn.refresh()Refetch lifecycle state from the server
turn.wait_for_completion(poll_interval_ms=...)Block until the turn reaches a terminal state
turn.stream(after_sequence_number=...)Reconnect to a running turn’s SSE
turn.list_events(order=...)Merged event log for a completed turn
turn.cancel()Cancel a running turn
session.list_turns()List turns in the session
session.get_turn(turn_id)Fetch a single turn by id
session.cancel()Cancel the running turn
Import is_event_delta, merge_event_delta, and event types from truefoundry_gateway_sdk.agents. Import UserMessage and content-part types from truefoundry_gateway_sdk.types.

Low-level reference (TrueFoundryGateway)

import os
from truefoundry_gateway_sdk import TrueFoundryGateway

client = TrueFoundryGateway(
    base_url=os.environ["TFY_GATEWAY_URL"],
    api_key=os.environ["TFY_API_KEY"],
)

create

client.agents.sessions.create(agent_name=...) -> GetSessionResponse
Create a conversation Session for a saved agent. The returned response wraps the session in .data.
ParamTypeRequiredDescription
agent_namestringYesName of the saved agent to invoke.

list

client.agents.sessions.list(agent_name=..., limit=10, order=None, page_token=None, start_timestamp=None, end_timestamp=None)
  -> SyncPager[Session, ListSessionsResponse]
List Sessions for a saved agent, newest-first by default. The pager auto-paginates when iterated.
ParamTypeRequiredDescription
agent_namestringYesFilter to sessions for a specific named agent.
limitintNoNumber of sessions fetched per page (not a total cap).
order"asc" | "desc"NoSort order by creation time. Defaults to "desc".
page_tokenstringNoPagination token from a previous page. Usually omitted — iteration handles paging.
start_timestampstringNoISO-8601 lower bound on session creation time.
end_timestampstringNoISO-8601 upper bound on session creation time.

get

client.agents.sessions.get(session_id) -> GetSessionResponse
Fetch an existing session by ID. The returned response wraps the session in .data.
ParamTypeRequiredDescription
session_idstringYesSession ID to retrieve.

cancel

client.agents.sessions.cancel(session_id) -> CancelSessionResponse
Cancel the running turn for a session. Idempotent.
ParamTypeRequiredDescription
session_idstringYesSession to cancel.

Session

The conversation context for a saved agent, returned by create and get in .data. Turns created within a session are chained automatically, so each turn sees the history of earlier ones. Key members:
MemberTypeDescription
idstringUnique session identifier. Persist it to resume later via get.
agent_namestringName of the saved agent this session belongs to.
titlestring | NoneOptional human-readable title for the session.
created_by_subjectSubjectSubject (user / service account) that created this session.
created_atstringISO-8601 timestamp of session creation.
updated_atstringISO-8601 timestamp of the last session update.

create_turn

client.agents.sessions.create_turn(session_id, input=None, previous_turn_id="auto")
  -> Iterator[TurnStreamingEvent]
Start or continue a turn within a session. Responds with a Server-Sent Events stream. The first event is turn.created; the stream closes with turn.done.
ParamTypeRequiredDescription
session_idstringYesSession to run the turn in.
inputTurnInputItem[]NoInput items for this turn. See Turn input. Omit to resume after mcp.auth_required.
previous_turn_idstring | "auto"NoTurn chaining point. Defaults to "auto", letting the server chain to the latest turn.

list_turns

client.agents.sessions.list_turns(session_id, page_token=None, limit=10)
  -> SyncPager[Turn, ListTurnsResponse]
List turns in a session, newest-first. The pager auto-paginates when iterated.
ParamTypeRequiredDescription
session_idstringYesSession to list turns for.
page_tokenstringNoPagination token from a previous page.
limitintNoNumber of turns fetched per page (not a total cap).

get_turn

client.agents.sessions.get_turn(session_id, turn_id) -> GetTurnResponse
Fetch a single turn by ID. The returned response wraps the turn in .data.
ParamTypeRequiredDescription
session_idstringYesSession the turn belongs to.
turn_idstringYesTurn ID to retrieve.

Turn

A single request/response cycle within a session, returned by list_turns and get_turn in .data. Transitions: runningdone | cancelled | error.
MemberTypeDescription
idstringUnique turn identifier (UUIDv7).
session_idstringThe session this turn belongs to.
previous_turn_idstring | NoneTurn ID this turn chains from, or None for the first turn.
created_by_subjectSubjectSubject (user / service account) that created this turn.
created_atstringISO-8601 timestamp of turn creation.
inputTurnInputItem[] | NoneThe Turn input that triggered this turn, if any.
stateTurnStateCached lifecycle state (running, done, cancelled, or error). Refetch with get_turn.

subscribe_to_turn

client.agents.sessions.subscribe_to_turn(session_id, turn_id, after_sequence_number=None)
  -> Iterator[TurnStreamingEvent]
Reconnect to a running turn’s live SSE stream. Pass after_sequence_number to resume after a known point. Closes when the turn reaches a terminal state. Use list_turn_events for completed turns.
ParamTypeRequiredDescription
session_idstringYesSession the turn belongs to.
turn_idstringYesTurn to subscribe to.
after_sequence_numberintNoResume after this sequence number.

list_turn_events

client.agents.sessions.list_turn_events(session_id, turn_id, page_token=None, limit=25, order=None)
  -> SyncPager[TurnEvent, ListEventsResponse]
Return a paginated snapshot of stored events for a completed turn. Pass order="asc" to replay forward. The pager auto-paginates when iterated.
ParamTypeRequiredDescription
session_idstringYesSession the turn belongs to.
turn_idstringYesTurn whose events to list.
page_tokenstringNoPagination token from a previous page.
limitintNoNumber of events fetched per page (not a total cap).
order"asc" | "desc"NoSort order by sequence number. Defaults to "asc".

TypeScript reference

Import the high-level client from truefoundry-gateway-sdk/agents. Method names below use camelCase; Turn input JSON shapes are the same in every language.
import { AgentSessionClient } from "truefoundry-gateway-sdk/agents";

const client = new AgentSessionClient({
  apiKey: process.env.TFY_API_KEY!,
  baseUrl: process.env.TFY_GATEWAY_URL!,
});

createSession

client.createSession({ agentName, title? }) -> Promise<AgentSession>
Create a conversation AgentSession for a saved agent.
ParamTypeRequiredDescription
agentNamestringYesName of the saved agent to invoke.
titlestringNoOptional human-readable title for the session.

listSessions

client.listSessions({ agentName, startTimestamp?, endTimestamp?, limit?, order?, pageToken? })
  -> Promise<Page<AgentSession>>
List AgentSession objects for a saved agent, newest-first. The returned Page is async-iterable and auto-paginates.
ParamTypeRequiredDescription
agentNamestringYesFilter to sessions for a specific named agent.
startTimestampstringNoISO-8601 lower bound on session creation time.
endTimestampstringNoISO-8601 upper bound on session creation time.
limitnumberNoNumber of sessions fetched per page (not a total cap).
order"asc" | "desc"NoSort order by creation time. Defaults to "desc".
pageTokenstringNoPagination token from a previous page. Usually omitted — iteration handles paging.

getSession

client.getSession({ sessionId }) -> Promise<AgentSession>
Fetch an existing session by ID.
ParamTypeRequiredDescription
sessionIdstringYesSession ID to retrieve.

AgentSession

The conversation context for a saved agent. Turns created within a session are chained automatically. Key members:
MemberTypeDescription
idstringUnique session identifier. Persist it to resume later via client.getSession({ sessionId }).
agentNamestringName of the saved agent this session belongs to.
titlestring | undefinedOptional human-readable title for the session.
createdBySubjectSubjectSubject (user / service account) that created this session.
createdAtstringISO-8601 timestamp of session creation.
updatedAtstringISO-8601 timestamp of the last session update.
prepareTurn(...)methodStage a turn locally and return a PreparedTurn with no network call. Start it with execute({ stream: true }) (stream events) or execute({ stream: false }) (wait for terminal state). See prepareTurn.
listTurns(...)methodReturn a Page<Turn> of turns in this session (default order: newest-first). Async-iterate the page to walk every turn.
getTurn({ turnId })methodFetch a single Turn by ID.
cancel()methodCancel the session and any currently running turn. Idempotent.

prepareTurn

session.prepareTurn({ input?, previousTurnId? }) -> PreparedTurn
Stage a turn in the session. Makes no network call and returns a PreparedTurn with no id yet. The turn is created server-side on the first execute() call:
  • execute({ stream: true }) — POST createTurn and stream the SSE response as { sequenceNumber, event } data objects.
  • execute({ stream: false, pollIntervalMs? }) — POST createTurn without streaming, then poll until the turn reaches a terminal state.
After execute() starts the turn, call stream(), refresh(), waitForCompletion(), listEvents(), or cancel() on the same object. Calling those methods before execute() raises.
ParamTypeRequiredDescription
inputTurnInputItem[]NoInput items for this turn. See Turn input. Omit to resume after mcp.auth_required.
previousTurnIdstring | "auto"NoTurn chaining point. Defaults to "auto".

PreparedTurn

Output of prepareTurn(). Not yet started — no HTTP until execute(). Identity fields delegate to the inner Turn once started (undefined until then).
MemberTypeDescription
idstring | undefinedTurn ID. Undefined until execute() starts the turn.
sessionAgentSessionThe session this turn belongs to.
previousTurnIdstring | undefinedTurn ID this turn chains from. Undefined until started.
createdBySubjectSubject | undefinedSubject that created this turn. Undefined until started.
createdAtstring | undefinedISO-8601 timestamp of turn creation. Undefined until started.
inputTurnInputItem[] | undefinedThe Turn input passed to prepareTurn(), if any.
stateTurnState | undefinedCached lifecycle state. Undefined until started; use refresh() to refresh.
execute({ stream: true })methodStart the turn and stream SSE data until terminal. Returns AsyncIterable<TurnStreamData>. Each item has { sequenceNumber, event }.
execute({ stream: false, pollIntervalMs? })methodStart the turn without streaming and block until terminal. Returns Promise<TurnState>. Default poll interval is 3000 ms (minimum 3000 ms).
stream({ afterSequenceNumber? })methodReconnect to a running turn’s live SSE stream after execute() has started it. Yields the same { sequenceNumber, event } shape. Raises if the turn has not been started.
refresh()methodRefetch lifecycle state from the server and return this. Raises if the turn has not been started.
waitForCompletion({ pollIntervalMs? })methodBlock until the turn reaches a terminal state. Raises if the turn has not been started.
listEvents(...)methodReturn a paginated snapshot of stored events. Async-iterate the returned Page. Raises if the turn has not been started.
cancel()methodRequest cancellation. Raises if the turn has not been started.

Turn

A started turn returned by listTurns(), getTurn(), or after PreparedTurn.execute(). Same methods as PreparedTurn except there is no execute() — the turn already exists server-side.
MemberTypeDescription
idstringUnique turn identifier (UUIDv7).
sessionAgentSessionThe session this turn belongs to.
previousTurnIdstring | undefinedTurn ID this turn chains from, or undefined for the first turn.
createdBySubjectSubjectSubject (user / service account) that created this turn.
createdAtstringISO-8601 timestamp of turn creation.
inputTurnInputItem[] | undefinedThe Turn input that triggered this turn, if any.
stateTurnStateCached lifecycle state (running, done, cancelled, or error). Updated in place by stream() and refresh().
stream({ afterSequenceNumber? })methodSubscribe to the turn’s live SSE stream. Resumes after afterSequenceNumber (default 0). Closes when the turn reaches a terminal state.
refresh()methodRefetch state from the server and return this.
waitForCompletion({ pollIntervalMs? })methodBlock until terminal. Returns immediately if already terminal.
listEvents(...)methodPaginated snapshot of stored events. Pass order: "asc" to replay forward.
cancel()methodRequest cancellation. Idempotent on terminal turns.

To define or configure the agent itself, see Create an agent.