Complete API reference for the Amp TypeScript SDK. This document provides detailed information about all functions, types, and interfaces.
# Install the Amp SDK using npm
npm install @sourcegraph/amp-sdk
# or yarn
yarn add @sourcegraph/amp-sdk
# Install or upgrade the Amp CLI used by the SDK (optional if a compatible version is already installed)
npx -y @sourcegraph/amp-sdk install The main function for executing Amp CLI commands programmatically.
function execute(options: ExecuteOptions): AsyncIterable<StreamMessage> Parameters
options (ExecuteOptions) - Configuration for the executionReturns
AsyncIterable<StreamMessage> - Stream of messages from the Amp CLIExample
import { execute } from '@sourcegraph/amp-sdk'
for await (const message of execute({
prompt: 'Analyze this codebase',
options: {
cwd: './my-project',
dangerouslyAllowAll: true,
},
})) {
if (message.type === 'assistant') {
console.log('Assistant:', message.message.content)
} else if (message.type === 'result') {
console.log('Final result:', message.result)
break
}
} Helper function to create properly formatted user input messages for streaming conversations.
function createUserMessage(text: string): UserInputMessage Parameters
text (string) - The text content for the user messageReturns
UserInputMessage - A formatted user input messageExample
import { createUserMessage } from '@sourcegraph/amp-sdk'
const message = createUserMessage('Analyze this code')
console.log(message)
// Output: { type: 'user', message: { role: 'user', content: [{ type: 'text', text: 'Analyze this code' }] } } Helper function to create permission objects for controlling tool usage.
function createPermission(
tool: string,
action: 'allow' | 'reject' | 'ask' | 'delegate',
options?: {
matches?: Record<string, PermissionMatchCondition>
context?: 'thread' | 'subagent'
to?: string
},
): Permission Parameters
tool (string) - The name of the tool to which this permission applies (supports glob patterns)action ('allow' | 'reject' | 'ask' | 'delegate') - How Amp should proceed when matchedoptions (object, optional) - Additional configuration for the permission matches (Record<string, PermissionMatchCondition>) - Match conditions for tool argumentscontext ('thread' | 'subagent') - Only apply this rule in specific contextto (string) - Command to delegate to (required when action is 'delegate')Returns
Permission - A permission object that can be used in the permissions arrayExamples
import { createPermission } from '@sourcegraph/amp-sdk'
// Allow all Bash commands
createPermission('Bash', 'allow')
// Allow specific git commands
createPermission('Bash', 'allow', {
matches: { cmd: 'git *' },
})
// Ask before allowing Read operations on sensitive paths
createPermission('Read', 'ask', {
matches: { path: '/etc/*' },
})
// Delegate web browsing to a custom command
createPermission('mcp__playwright__*', 'delegate', {
to: 'node browse.js',
})
// Only apply in subagent context
createPermission('Bash', 'reject', {
context: 'subagent',
}) 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 threadReturns
Promise<string> - The thread IDExample
import { threads } from '@sourcegraph/amp-sdk'
// Create a new private thread
const threadId = await threads.new({ visibility: 'private' })
console.log('Created thread:', threadId) Get a thread rendered as markdown.
async function threads.markdown(options: ThreadsMarkdownOptions): Promise<string> Parameters
options (ThreadsMarkdownOptions) - Options containing the thread IDReturns
Promise<string> - The thread content as markdownExample
import { threads } from '@sourcegraph/amp-sdk'
// Get thread content as markdown
const markdown = await threads.markdown({ threadId: 'T-abc123-def456' })
console.log(markdown) 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 |
Configuration options that map to Amp CLI flags.
interface AmpOptions {
cwd?: string
mode?: 'smart' | 'rush' | 'deep'
dangerouslyAllowAll?: boolean
archive?: boolean
visibility?: 'public' | 'private' | 'team'
settingsFile?: string
logLevel?: 'debug' | 'info' | 'warn' | 'error' | 'audit'
logFile?: string
mcpConfig?: string | MCPConfig
env?: Record<string, string>
continue?: boolean | string
toolbox?: string
skills?: string
permissions?: Permission[]
} Properties
| Property | Type | Default | Description |
|---|---|---|---|
cwd | string | process.cwd() | Current working directory for execution |
mode | 'smart' \| 'rush' \| 'deep' | 'smart' | Agent mode - controls model, system prompt, and tool selection |
dangerouslyAllowAll | boolean | false | Allow all tool usage without permission prompts |
archive | boolean | false | Archive the thread after execution completes |
visibility | 'public' \| 'private' \| 'team' | 'team' | Thread visibility level |
settingsFile | string | - | Path to custom settings file |
logLevel | 'debug' \| 'info' \| 'warn' \| 'error' \| 'audit' | 'info' | 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 |
toolbox | string | - | Folder path with toolbox scripts |
skills | string | - | Folder path with custom skills |
permissions | Permission[] | - | Permission rules for tool usage |
labels | string[] | - | Labels to add to the thread |
The SDK streams various message types during execution. All messages implement the base StreamMessage type.
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: 'connected' | 'connecting' | 'connection-failed'
}>
} 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 |
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 |
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 |
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 |
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 |
Plain text content block.
interface TextContent {
type: 'text'
text: string
} Tool execution request.
interface ToolUseContent {
type: 'tool_use'
id: string
name: string
input: Record<string, unknown>
} Result from tool execution.
interface ToolResultContent {
type: 'tool_result'
tool_use_id: string
content: string
is_error: boolean
} 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 |
Formatted user input message for streaming conversations.
interface UserInputMessage {
type: 'user'
message: {
role: 'user'
content: Array<{
type: 'text'
text: string
}>
}
} 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 |
Options for creating a new thread.
interface ThreadsNewOptions {
visibility?: 'private' | 'public' | 'workspace' | 'group'
} Properties
| Property | Type | Required | Description |
|---|---|---|---|
visibility | 'private' \| 'public' \| 'workspace' \| 'group' | No | Thread visibility |
Options for getting thread markdown.
interface ThreadsMarkdownOptions {
threadId: string
} Properties
| Property | Type | Required | Description |
|---|---|---|---|
threadId | string | Yes | The thread ID to get markdown for |
Individual permission rule for controlling tool usage.
interface Permission {
tool: string
matches?: Record<string, PermissionMatchCondition>
action: 'allow' | 'reject' | 'ask' | 'delegate'
context?: 'thread' | 'subagent'
to?: string
} Properties
| Property | Type | Required | Description |
|---|---|---|---|
tool | string | Yes | Tool name (supports glob patterns like Bash or mcp__*) |
matches | Record<string, PermissionMatchCondition> | No | Match conditions for tool arguments |
action | 'allow' \| 'reject' \| 'ask' \| 'delegate' | Yes | How Amp should proceed when the rule matches |
context | 'thread' \| 'subagent' | No | Apply rule only in main thread or sub-agents |
to | string | No | Command to delegate to (required when action is delegate) |
Example
import { execute, createPermission } from '@sourcegraph/amp-sdk'
for await (const message of execute({
prompt: 'Deploy the application',
options: {
permissions: [
// Allow git commands
createPermission('Bash', 'allow', { matches: { cmd: 'git *' } }),
// Allow reading files
createPermission('Read', 'allow'),
],
},
})) {
// Handle messages
} Match condition for tool arguments. Supports strings (with glob patterns or regex), arrays (OR logic), booleans, numbers, null, undefined, and nested objects.
type PermissionMatchCondition =
| string
| PermissionMatchCondition[]
| { [key: string]: PermissionMatchCondition }
| boolean
| number
| null
| undefined Examples
// String pattern with wildcard
{ cmd: 'npm *' }
// Array for OR logic
{ cmd: ['npm install', 'npm test', 'npm run build'] }
// Regex pattern
{ cmd: '/^git (status|log|diff)$/' }
// Nested object matching
{ env: { NODE_ENV: 'production' } }