Create Session
Creates a session instance that binds an agent with a runtime environment. A full snapshot of the agent's latest version is captured at session creation. Session-level agent configuration overrides and MCP request headers are supported.
Prerequisites
Endpoint and authentication configuration must be completed. For details, see Overview and authentication. Before creating a session, you need an agent and an environment. For details, see Agent and Environment. To mount a Bailian memory store, the Bailian memory service must be activated.
Endpoint
/sessionsRequest body
agentobjectRequiredThe bound agent reference object; pass only id to simply reference the agent. Can pin a version and optionally establish session-level overrides—see Session-level configuration overrides
agent properties
idstringAgent ID, format agent_xxx
versionintegerVersion to pin; latest if omitted
environment_idstringRequiredThe bound environment ID. If the environment has pre-installed packages configured, warm-up may be required after creation; a preparing environment cannot be bound to sessions (returns invalid_parameter), so wait for warm-up to complete
sandboxobjectOptionalSandbox snapshot persistence configuration. If omitted, the original session creation behavior is preserved
enable_snapshotbooleanRequiredWhether to enable snapshot persistence for the current session. Required when sandbox is passed
snapshot_persistent_secondsintegerConditionalRetention period of a single snapshot in seconds, ranging from 86400 to 2592000 (1–30 days). Required when enable_snapshot=true
titlestringOptionalSession title for easy identification in lists
resourcesarrayOptionalResources to mount at creation.
File items
type: fixed asfilefile_id: uploaded file IDmount_path: mount path; must start with/uploads/, the actual path is prefixed with/mnt/session
Memory items
type: fixed asmemory_storeprovider:default/agentstudio_memory, defaults todefaultwhen omittedmemory_store_id: requiredentity_id: required for Bailian memoryaccess:read_only/read_write, defaults toread_writedescription: mount purpose description for Bailian memoryproject_ids: Bailian factual and skill memory rule IDs; at most 5 per mount in totalprofile_schema: Bailian profile schema ID; at most oneinstructions: mount instruction for built-in memory, up to 4096 characters
The mount path for built-in memory is generated by the server; Bailian memory has no mount path. See Memory Store
vault_idsarray of stringOptionalVault ID list. Injects credentials from the specified vaults into the session runtime environment, allowing the agent to access the corresponding secrets
metadataobjectOptionalCustom key-value pairs for business use; does not affect model behavior
environment_variablesobjectOptionalEnvironment variables injected into the session runtime as string key-value pairs; sandbox code can read them directly by name
mcp_configsarrayOptionalSession-level MCP request headers, independent of agent—see Session-level MCP request headers. Defaults to an empty array when omitted
provider: accepts onlydefaultoragentstudio_memory; an explicitnull, an empty string, or any other value returns a parameter error.entity_id: used only for Bailian memory; it is the entity ID bound to the mount, not the cloud account UID or a top-level Session field.project_ids: if omitted or an empty array, the default Bailian memory rules are used.profile_schema: if omitted, the profile capability is not enabled and does not count toward the 5-rule limit.- Built-in memory: continues to use
memory_store_id,access, andinstructions.
NoteWhen one session binds multiple vaults, secret_name values must be unique across vaults and must not share a prefix (for example, API_KEY and API_KEY_V2). Otherwise, session creation returns 400 invalid_parameter ("Invalid request").
mcp_configs properties
providerstringdefault or agentstudio_memory
entity_idstringEntity ID for the Bailian memory binding
project_idsarray<string>Bailian memory project IDs; defaults apply when omitted or empty
profile_schemastringUser profile schema ID
memory_store_idstringMemory store ID
accessstringMemory store access mode
instructionsstringMemory usage instructions
Request example
curl -X POST "$AGENTSTUDIO_URL/sessions" \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"agent": {"type": "agent", "id": "agent_xxx"},
"environment_id": "env_xxx",
"title": "Q3 sales data analysis",
"resources": [
{"type": "file", "file_id": "file_xxx", "mount_path": "/uploads/workspace/data.csv"}
],
"vault_ids": ["vlt_xxx"],
"metadata": {"biz_ticket_id": "1234"},
"environment_variables": {"API_BASE_URL": "https://api.example.com", "LOG_LEVEL": "info"}
}'
session = client.sessions.create(
agent={"type": "agent", "id": "agent_xxx"},
environment_id="env_xxx",
title="Q3 sales data analysis",
resources=[
{"type": "file", "file_id": "file_xxx", "mount_path": "/uploads/workspace/data.csv"},
],
vault_ids=["vlt_xxx"],
metadata={"biz_ticket_id": "1234"},
environment_variables={"API_BASE_URL": "https://api.example.com", "LOG_LEVEL": "info"},
)
print(session.id, session.status)
Map<String, String> metadata = new HashMap<>();
metadata.put("biz_ticket_id", "1234");
Map<String, String> environmentVariables = new HashMap<>();
environmentVariables.put("API_BASE_URL", "https://api.example.com");
environmentVariables.put("LOG_LEVEL", "info");
Session session = client.sessions().create(SessionCreateParam.builder()
.agent(SessionAgent.ofOverride(Map.of("type", "agent", "id", "agent_xxx")))
.environmentId("env_xxx")
.title("Q3 sales data analysis")
.resources(List.of(SessionResource.builder()
.type("file")
.fileId("file_xxx")
.mountPath("/uploads/workspace/data.csv")
.build()))
.vaultIds(List.of("vlt_xxx"))
.metadata(metadata)
.environmentVariables(environmentVariables)
.build());
System.out.println(session.getId() + " " + session.getStatus());
Bailian Memory Mount Example
To mount a Bailian memory store, set provider to agentstudio_memory and provide entity_id:
{
"agent": {
"type": "agent",
"id": "agent_xxx"
},
"environment_id": "env_xxx",
"resources": [
{
"type": "memory_store",
"provider": "agentstudio_memory",
"memory_store_id": "0123456789abcdef0123456789abcdef",
"entity_id": "customer_001",
"access": "read_write",
"description": "Save customer-confirmed business agreements, reusable experience, and communication preferences",
"project_ids": ["fact_rule_demo", "skill_rule_demo"],
"profile_schema": "profile_schema_demo"
}
]
}
memory_store_id is the Bailian memory store ID; the memstore_ prefix is not required. For default behavior of rules and profile schemas, see Memory Store.
To enable sandbox persistence, add sandbox to the request body, for example:
{
"sandbox": {
"enable_snapshot": true,
"snapshot_persistent_seconds": 172800
}
}
If omitted, persistence is disabled. For restore rules and expiry behavior, see Sandbox persistence.
Session-level configuration overrides
The agent object can simply reference the agent, or carry override fields to establish session-level overrides: only the configuration snapshot of the current session is modified—the agent itself is never changed, and multiple sessions can reuse the same agent with different customizations. The object fields are:
| Field | Required | Type | Description |
|---|---|---|---|
type | No | string | agent (reference only) or agent_with_overrides (reference with overrides). When carrying override fields, agent_with_overrides must be set explicitly; otherwise invalid_parameter is returned |
id | Yes | string | Agent ID |
version | No | integer | Agent version to pin; the current latest version is used when omitted. Returns not_found if the version does not exist |
system | No | string / null | Overrides the system prompt. Inherits the agent's source configuration when omitted; an empty string explicitly uses an empty prompt |
tools | No | array / null | Overrides the tool configuration; same structure as tools in Create Agent |
mcp_servers | No | array / null | Overrides the mounted MCP server list; same structure as mcp_servers in Create Agent |
skills | No | array / null | Overrides the mounted skill list; same structure as skills in Create Agent |
Semantics of override field values (consistent between createSession and Update Session):
| Value | Effect |
|---|---|
| Omitted | Inherit the agent's source configuration |
null | Do not establish an override; inherit the source configuration |
[] (array fields) | Explicitly override to empty |
"" (only for system) | Explicitly use an empty prompt |
Session-level MCP request headers
mcp_configs injects custom headers into every request to the specified MCP servers, commonly used to pass tenant IDs or auth tokens. Each item contains mcp_server_name (MCP server name) and headers (key-value pairs where both key and value are strings). Passing a non-existent MCP server name does not raise an error; the configuration simply has no effect. For the per-session workflow and examples, see Custom MCP and Skills.
Full request example for creating a session:
curl -X POST "$AGENTSTUDIO_URL/sessions" \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"agent": {
"type": "agent_with_overrides",
"id": "agent_xxx",
"system": "You are a data verification assistant dedicated to this session. Output only verification conclusions."
},
"environment_id": "env_xxx",
"mcp_configs": [
{"mcp_server_name": "crm", "headers": {"X-Tenant-Id": "tenant-demo"}}
]
}'
session = client.sessions.create(
agent={"type": "agent_with_overrides", "id": "agent_xxx",
"system": "You are a data verification assistant dedicated to this session. Output only verification conclusions."},
environment_id="env_xxx",
mcp_configs=[{"mcp_server_name": "crm", "headers": {"X-Tenant-Id": "tenant-demo"}}],
)
Map<String, Object> agentOverride = Map.of(
"type", "agent_with_overrides",
"id", "agent_xxx",
"system", "You are a data verification assistant dedicated to this session. Output only verification conclusions.");
Map<String, String> headers = Map.of("X-Tenant-Id", "tenant-demo");
Session session = client.sessions().create(SessionCreateParam.builder()
.agent(agentOverride)
.environmentId("env_xxx")
.mcpConfigs(List.of(Map.of(
"mcp_server_name", "crm",
"headers", headers)))
.build());
Response fields
The response is a Session object with the following fields:
idstringSession ID, format sesn_<ULID>
typestringFixed as session
statusstringSession status: idle / running / terminated. Newly created sessions are idle
agentobjectFull agent configuration snapshot, including id/version/name/model/system/tools, etc.; session-level overrides are merged into the snapshot
agent properties
idstringAgent ID, format agent_xxx
versionintegerVersion to pin; latest if omitted
environment_idstringThe bound environment ID
resourcesarrayMounted resource list.
File items
id: resource IDtype: resource typefile_id: internal copy IDmount_path: full path with prefix
Memory items
id: server-generated mount ID, different frommemory_store_id; not passed at creationtype: resource typeprovider: memory providermemory_store_id: memory store IDname: optional and may be emptyaccess: access permission
Bailian memory items
entity_id: Bailian memory entity IDproject_ids: Bailian factual and skill memory rule IDsprofile_schema: Bailian profile schema IDdescription: the mount description saved at creation, which can be empty if not provided- Does not return
mount_path
Built-in memory items
file_id: alwaysnulldescription: store metadatainstructions: mount instructionmount_path: server-generated, e.g./mnt/memory/<name>
titlestringSession title
metadataobjectCustom business key-value pairs
sandboxobjectSandbox snapshot persistence configuration. Omitted when not configured
enable_snapshotbooleanWhether snapshot persistence is enabled for the current session
snapshot_persistent_secondsintegerRetention period of the configured snapshot in seconds; omitted when not configured
archived_atstring / nullArchive time; null when not archived
created_atstringCreation time (ISO 8601)
updated_atstringLast update time (ISO 8601)
request_idstringUnique identifier for this request
environment_variablesobjectEnvironment variables injected into the session runtime as string key-value pairs; sandbox code can read them directly by name
A Bailian memory mount returns only the rule and profile schema IDs selected at creation; no default rules or profile schemas are added, and memory bodies, profile values, and full rule definitions are not returned.
This response does not contain mcp_configs; query it via Get Session.
Response example
The session details embed a full agent snapshot.
{
"id": "sesn_xxx",
"type": "session",
"status": "idle",
"agent": {
"id": "agent_xxx",
"type": "agent",
"version": 1,
"name": "data-analyst",
"description": null,
"model": {"id": "qwen3.7-max"},
"system": "You are a data analysis expert who uses pandas to process CSV files.",
"tools": []
},
"environment_id": "env_xxx",
"title": "Q3 sales data analysis",
"resources": [
{
"id": "sesrsc_xxx",
"type": "file",
"file_id": "file_xxx",
"mount_path": "/mnt/session/uploads/workspace/data.csv",
"created_at": "2026-05-28T08:23:11Z",
"updated_at": "2026-05-28T08:23:11Z"
}
],
"metadata": {"biz_ticket_id": "1234"},
"archived_at": null,
"created_at": "2026-05-28T08:23:11Z",
"updated_at": "2026-05-28T08:23:11Z",
"request_id": "xxx",
"environment_variables": {"API_BASE_URL": "https://api.example.com", "LOG_LEVEL": "info"}
}
Sandbox configuration response example
When a session is created with sandbox persistence enabled, sandbox returns only the configuration:
{
"sandbox": {
"enable_snapshot": true,
"snapshot_persistent_seconds": 172800
}
}
Query the current snapshot status and statistics through Get Session.
Configuration lock
A full snapshot of the agent's latest version is captured at session creation (embedded in the agent field of the session details). Subsequent edits to the agent only affect new sessions; existing sessions continue using the configuration from the snapshot. Session-level configuration is currently API-only; sessions created in the console are read-only snapshots. Session-level configuration can be modified after creation—see Update Session.