TypeScript SDK
API reference for the Amp TypeScript SDK.
Installation
# Install the Amp SDK using npm
npm install @ampcode/sdk
# or yarn
yarn add @ampcode/sdk
# Optional: manually install the Amp CLI, already a dependency
npx -y @ampcode/sdk install If you need to use Amp before Amp Neo, install the legacy SDK release @ampcode/sdk@0.1.0-20260528044221-ge0e19fa:
npm install @ampcode/sdk@0.1.0-20260528044221-ge0e19fa Functions
execute()
The main function for executing Amp CLI commands programmatically.
function execute(options: ExecuteOptions): AsyncIterable<StreamMessage> Parameters
options(ExecuteOptions) - Configuration for the execution
Returns
AsyncIterable<StreamMessage>- Stream of messages from the Amp CLI
Example
import { execute } from '@ampcode/sdk'
for await (const message of execute({
prompt: 'Analyze this codebase',
options: {
cwd: './my-project',
},
})) {
if (message.type === 'assistant') {
console.log('Assistant:', message.message.content)
} else if (message.type === 'result' && !message.is_error) {
console.log('Final result:', message.result)
break
}
} createUserMessage()
Helper function to create properly formatted user input messages for streaming conversations.
function createUserMessage(text: string, options?: { requestId?: string }): UserInputMessage Parameters
text(string) - The text content for the user messageoptions.requestId(string, optional) - A 1–256 character ID. Reusing it for a retry on the same thread prevents Amp from creating another user message.
Returns
UserInputMessage- A formatted user input message
Example
import { createUserMessage } from '@ampcode/sdk'
const message = createUserMessage('Analyze this code', { requestId: 'analysis-123' })
console.log(message)
// Output: { type: 'user', requestId: 'analysis-123', message: { role: 'user', content: [{ type: 'text', text: 'Analyze this code' }] } } threads.new()
Create a new empty thread and return its ID.
async function threads.new(options?: ThreadsNewOptions): Promise<string> Parameters
options(ThreadsNewOptions, optional) - Configuration for the new thread
Returns
Promise<string>- The thread ID
Example
import { threads } from '@ampcode/sdk'
// Create a new private thread
const threadId = await threads.new({ visibility: 'private' })
console.log('Created thread:', threadId) threads.markdown()
Get a thread rendered as markdown.
async function threads.markdown(options: ThreadsMarkdownOptions): Promise<string> Parameters
options(ThreadsMarkdownOptions) - Options containing the thread ID
Returns
Promise<string>- The thread content as markdown
Example
import { threads } from '@ampcode/sdk'
// Get thread content as markdown
const markdown = await threads.markdown({ threadId: 'T-abc123-def456' })
console.log(markdown) threads.setMultiplayer()
Turn multiplayer on or off. This only works for the owner of a shared thread that runs in an orb or on a shared runner.
async function threads.setMultiplayer(options: ThreadsSetMultiplayerOptions): Promise<void> Parameters
options(ThreadsSetMultiplayerOptions) - The thread ID, enabled flag, and optional multiplayer duration
Returns
Promise<void>
Example
import { threads } from '@ampcode/sdk'
// Enable multiplayer for the default duration (currently 1 week)
await threads.setMultiplayer({ threadId: 'T-abc123-def456' })
// Enable multiplayer for 12 hours
await threads.setMultiplayer({ threadId: 'T-abc123-def456', hours: 12 })
// Disable multiplayer
await threads.setMultiplayer({ threadId: 'T-abc123-def456', enabled: false }) Types
ExecuteOptions
Configuration options for the execute() function.
interface ExecuteOptions {
prompt: string | AsyncIterable<UserInputMessage>
options?: AmpOptions
signal?: AbortSignal
} Properties
| Property | Type | Required | Description |
|---|---|---|---|
prompt | string \| AsyncIterable<UserInputMessage> | Yes | The input prompt as a string or async iterable of user messages for multi-turn conversations |
options | AmpOptions | No | CLI configuration options |
signal | AbortSignal | No | Signal for cancellation support |
AmpOptions
Configuration options that map to Amp CLI flags.
interface AmpOptions {
cwd?: string
mode?: string // Prefer 'low', 'medium', 'high', or 'ultra'
effort?: 'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max'
noArchiveAfterExecute?: boolean
visibility?: 'private' | 'unlisted' | 'workspace' | 'group'
settingsFile?: string
logLevel?: 'debug' | 'info' | 'warn' | 'error' | 'audit'
logFile?: string
mcpConfig?: string | MCPConfig
env?: Record<string, string>
continue?: boolean | string
skills?: string
enabledTools?: string[]
labels?: string[]
thinking?: boolean
executor?: 'local' | 'orb' | 'runner'
runnerId?: string
runnerDir?: string
project?: string
title?: string
} The built-in modes are 'low', 'medium', 'high', and 'ultra'. You can also pass a
string for a custom plugin-defined mode.
executor defaults to local execution. executor: 'orb' runs the agent in an orb; executor: 'runner' runs it on one of your runners, identified by runnerId. Set runnerDir to the
absolute path of one directory the runner serves, or omit it to use its starting directory.
Each thread has one working directory; use separate execute() calls for multiple directories.
Continuing a thread ignores this option and keeps its existing directory. cwd only sets the
local CLI subprocess directory, not the remote runner directory.
With either remote executor, prompt must be a string rather than streaming input, and local-only
options such as enabledTools, skills, and mcpConfig are ignored with a warning; configure
those in the Amp project or on the runner instead. Plugin agent modes must be loaded on the
runner. project requires orb execution; when it is omitted, Amp may infer a project from the Git
remotes under cwd, or start the orb without a repository if none match.
Properties
| Property | Type | Default | Description |
|---|---|---|---|
cwd | string | process.cwd() | Working directory of the local CLI subprocess |
mode | string | 'medium' | Prefer 'low', 'medium', 'high', or 'ultra'; custom plugin-defined mode strings are also accepted |
effort | 'none' \| 'minimal' \| 'low' \| 'medium' \| 'high' \| 'xhigh' \| 'max' | - | Reasoning effort for supported modes |
noArchiveAfterExecute | boolean | false | Leave new execute threads unarchived after execution completes |
visibility | 'private' \| 'unlisted' \| 'workspace' \| 'group' | 'workspace' | Thread visibility level |
settingsFile | string | - | Path to custom settings file |
logLevel | 'debug' \| 'info' \| 'warn' \| 'error' \| 'audit' | undefined | Logging verbosity level |
logFile | string | - | Path to write logs |
continue | boolean \| string | false | Continue most recent thread (true) or specific thread by ID (string) |
mcpConfig | string \| MCPConfig | - | MCP server configuration as JSON string, or config object |
env | Record<string, string> | - | Additional environment variables |
skills | string | - | Folder path with custom skills |
enabledTools | string[] | - | Tool name patterns to enable (maps to amp.tools.enable) |
labels | string[] | - | Labels to add to the thread |
thinking | boolean | false | Include thinking blocks in the result stream |
executor | 'local' \| 'orb' \| 'runner' | 'local' | Run in the local CLI process, a remote orb, or one of your runners |
runnerId | string | - | Runner ID for a new runner thread; requires executor: 'runner' |
runnerDir | string | - | Absolute path to one served directory for a new runner thread; requires executor: 'runner' |
project | string | Inferred | Amp project for a new orb thread; requires executor: 'orb' |
title | string | - | Title for a new thread, up to 256 characters |
Message Types
The SDK streams various message types during execution. All messages implement the base StreamMessage type.
SystemMessage
Initial message containing session information and available tools.
interface SystemMessage {
type: 'system'
subtype: 'init'
session_id: string
cwd: string
tools: string[]
mcp_servers: Array<{
name: string
status:
| 'awaiting-approval'
| 'authenticating'
| 'connecting'
| 'reconnecting'
| 'connected'
| 'denied'
| 'failed'
| 'blocked-by-registry'
}>
} Properties
| Property | Type | Description |
|---|---|---|
session_id | string | Unique identifier for this execution session |
cwd | string | Current working directory |
tools | string[] | List of available tool names |
mcp_servers | Array<{name: string, status: string}> | Status of MCP servers |
AssistantMessage
AI assistant responses with text content and tool usage.
interface AssistantMessage {
type: 'assistant'
session_id: string
message: {
id: string
type: 'message'
role: 'assistant'
model: string
content: Array<TextContent | ToolUseContent>
stop_reason: 'end_turn' | 'tool_use' | 'max_tokens' | null
stop_sequence: string | null
usage?: Usage
}
parent_tool_use_id: string | null
} Properties
| Property | Type | Description |
|---|---|---|
session_id | string | Unique identifier for this execution session |
message | object | The assistant’s message content |
parent_tool_use_id | string \| null | ID of parent tool use if this is a tool response |
UserMessage
User input and tool results.
interface UserMessage {
type: 'user'
session_id: string
message: {
role: 'user'
content: Array<TextContent | ToolResultContent>
}
parent_tool_use_id: string | null
} Properties
| Property | Type | Description |
|---|---|---|
session_id | string | Unique identifier for this execution session |
message | object | The user’s message content |
parent_tool_use_id | string \| null | ID of parent tool use if this is a tool response |
ResultMessage
Final successful execution result.
interface ResultMessage {
type: 'result'
subtype: 'success'
session_id: string
is_error: false
result: string
duration_ms: number
num_turns: number
usage?: Usage
permission_denials?: string[]
} Properties
| Property | Type | Description |
|---|---|---|
session_id | string | Unique identifier for this execution session |
result | string | The final result from the assistant |
duration_ms | number | Total execution time in milliseconds |
num_turns | number | Number of conversation turns |
usage | Usage | Token usage information |
permission_denials | string[] | List of permissions that were denied |
ErrorResultMessage
Final error result indicating execution failure.
interface ErrorResultMessage {
type: 'result'
subtype: 'error_during_execution' | 'error_max_turns'
session_id: string
is_error: true
error: string
duration_ms: number
num_turns: number
usage?: Usage
permission_denials?: string[]
} Properties
| Property | Type | Description |
|---|---|---|
session_id | string | Unique identifier for this execution session |
error | string | Error message describing what went wrong |
duration_ms | number | Total execution time in milliseconds |
num_turns | number | Number of conversation turns |
usage | Usage | Token usage information |
permission_denials | string[] | List of permissions that were denied |
TextContent
Plain text content block.
interface TextContent {
type: 'text'
text: string
} ToolUseContent
Tool execution request.
interface ToolUseContent {
type: 'tool_use'
id: string
name: string
input: Record<string, unknown>
} ToolResultContent
Result from tool execution.
interface ToolResultContent {
type: 'tool_result'
tool_use_id: string
content: string
is_error: boolean
} Usage
Token usage and billing information from API calls.
interface Usage {
input_tokens: number
cache_creation_input_tokens?: number
cache_read_input_tokens?: number
output_tokens: number
service_tier?: string
} Properties
| Property | Type | Description |
|---|---|---|
input_tokens | number | Number of input tokens used |
cache_creation_input_tokens | number | Tokens used for cache creation |
cache_read_input_tokens | number | Tokens read from cache |
output_tokens | number | Number of output tokens generated |
service_tier | string | Service tier used for this request |
Input Types
UserInputMessage
Formatted user input message for streaming conversations.
interface UserInputMessage {
type: 'user'
requestId?: string
message: {
role: 'user'
content: Array<{
type: 'text'
text: string
}>
}
} MCPConfig
Configuration for MCP (Model Context Protocol) servers. Supports both stdio-based and HTTP-based servers.
type MCPConfig = Record<string, MCPServer>
// MCPServer is a union of stdio and HTTP server configurations MCPServer accepts either a stdio server config (with command) or an HTTP server config (with url):
const mcpConfig: MCPConfig = {
playwright: { command: 'npx', args: ['-y', '@playwright/mcp'] },
remote: { url: 'https://api.example.com/mcp' },
} Stdio server properties:
| Property | Type | Required | Description |
|---|---|---|---|
command | string | Yes | Command to start the MCP server |
args | string[] | No | Command line arguments |
env | Record<string, string> | No | Environment variables for the server |
disabled | boolean | No | Whether this server is disabled |
HTTP server properties:
| Property | Type | Required | Description |
|---|---|---|---|
url | string | Yes | URL of the HTTP MCP server |
headers | Record<string, string> | No | HTTP headers to send with requests |
transport | string | No | Transport type (e.g., “sse”) |
oauth | object | No | OAuth configuration for authentication |
disabled | boolean | No | Whether this server is disabled |
ThreadsNewOptions
Options for creating a new thread.
interface ThreadsNewOptions {
visibility?: 'private' | 'unlisted' | 'workspace' | 'group'
} Properties
| Property | Type | Required | Description |
|---|---|---|---|
visibility | 'private' \| 'unlisted' \| 'workspace' \| 'group' | No | Thread visibility |
ThreadsMarkdownOptions
Options for getting thread markdown.
interface ThreadsMarkdownOptions {
threadId: string
} Properties
| Property | Type | Required | Description |
|---|---|---|---|
threadId | string | Yes | The thread ID to get markdown for |
ThreadsSetMultiplayerOptions
Options for enabling or disabling multiplayer. The duration options are summed; the total must be between 5 minutes and 7 days. When enabled is true and no duration is given, the server default (currently 1 week) is used. Duration options are not allowed when enabled is false.
interface ThreadsSetMultiplayerOptions {
threadId: string
enabled?: boolean
minutes?: number
hours?: number
days?: number
weeks?: number
} Properties
| Property | Type | Required | Description |
|---|---|---|---|
threadId | string | Yes | The thread ID to update |
enabled | boolean | No | Whether multiplayer is enabled (default true) |
minutes | number | No | Multiplayer duration in minutes |
hours | number | No | Multiplayer duration in hours |
days | number | No | Multiplayer duration in days |
weeks | number | No | Multiplayer duration in weeks |
Requirements
- Node.js 18 or higher