Amp SDK 允许你在 TypeScript 程序中代码式用使 Amp 代理。
Amp SDK 推供下列功能:
以下是使用 Amp SDK 可以构建的一些示例:
# Install the Amp SDK using npm
npm install @ampcode/sdk
# or yarn
yarn add @ampcode/sdk
# Install or upgrade the Amp CLI used by the SDK (optional if a compatible version is already installed)
npx -y @ampcode/sdk install对于 TypeScript SDK 用户,Amp CLI 必须至少是已安装 SDK 版本所锁定的版本。如果你的组织已经通过 Homebrew、Artifactory 或其他内部渠道安装了 Amp CLI,只要其版本足够新即可继续使用。
安装完成后,将你的访问令牌添加到环境变量中。你可以在 ampcode.com/settings.
export AMP_API_KEY=sgamp_your_access_token_here 如果你已经在本地安装了 Amp CLI,你可以使用以下命令登录 amp login.
现在你已经安装了 SDK 并设置了访问令牌,你可以开始使用 execute() 函数:
import { execute } from '@ampcode/sdk'
// Simple execution - get the final result
for await (const message of execute({ prompt: 'What files are in this directory?' })) {
if (message.type === 'result' && !message.is_error) {
console.log('Result:', message.result)
break
}
} execute() 函数只需要你提供一个 prompt 即可开始。SDK 在代理工作时流式传输消息,让你可以处理响应并将其直接集成到你的应用程序中。
SDK 在代理执行时流式传输不同类型的消息:
for await (const message of execute({ prompt: 'Run tests' })) {
if (message.type === 'system') {
// Session info, available tools, MCP servers
console.log('Available tools:', message.tools)
} else if (message.type === 'assistant') {
// AI responses and tool usage
console.log('Assistant is working...')
} else if (message.type === 'result') {
// Final result (success or error)
console.log('Done:', message.result)
}
}当你只需要最终结果而不需要处理流式传输时:
async function getResult(prompt: string): Promise<string> {
for await (const message of execute({ prompt, options: { dangerouslyAllowAll: true } })) {
if (message.type === 'result') {
if (message.is_error) {
throw new Error(message.error)
}
return message.result
}
}
throw new Error('No result received')
}
// Usage
try {
const result = await getResult('List all TypeScript files in this project')
console.log('Found files:', result)
} catch (error) {
console.error('Failed:', error.message)
}跨多次交互继续对话:
// Continue the most recent conversation
for await (const message of execute({
prompt: 'What was the last error you found?',
options: { continue: true },
})) {
if (message.type === 'result') {
console.log(message.result)
}
}
// Continue a specific thread by ID
for await (const message of execute({
prompt: 'Can you update that code we discussed?',
options: { continue: 'T-abc123-def456' },
})) {
if (message.type === 'result') {
console.log(message.result)
}
}对于自动化场景,允许工具无需批准提示即可运行:
const options = {
dangerouslyAllowAll: true, // Allow tools without approval prompts
}
for await (const message of execute({
prompt: 'Make changes without asking for approval',
options,
})) {
// Handle messages...
}指定 Amp 的运行位置:
for await (const message of execute({
prompt: 'Refactor the auth module',
options: { cwd: './my-project' },
})) {
// Process messages...
}查看底层发生了什么:
for await (const message of execute({
prompt: 'Analyze this project',
options: {
logLevel: 'debug', // Shows CLI command in console
logFile: './amp-debug.log', // Optional: write logs to file
},
})) {
// Process messages
}选择要使用的 Agent 模式。模式控制模型、系统提示词和工具选择:
for await (const message of execute({
prompt: 'Quickly fix this typo',
options: {
mode: 'rush', // Use rush mode for faster responses
},
})) {
// Process messages
}可用模式:
smart (默认):具备完整功能的平衡模式rush:更快的响应和精简的工具使用deep:用于复杂任务的扩展推理为 execute()创建的对话添加标签:
for await (const message of execute({
prompt: 'Summarize this repo',
options: {
labels: ['sdk', 'summary'],
},
})) {
if (message.type === 'result') {
console.log(message.result)
break
}
}控制谁可以查看 execute()创建的对话添加标签:
for await (const message of execute({
prompt: 'Analyze this private codebase',
options: {
visibility: 'private', // Only you can see this thread
},
})) {
if (message.type === 'result') {
console.log(message.result)
break
}
}可用可见性级别:
workspace (默认):对所有工作区成员可见private:仅对你可见public:对任何有链接的人可见group:对你的用户组成员可见(企业版)为本次运行传入权限插件规则:
import { execute, createPermission } from '@ampcode/sdk'
for await (const message of execute({
prompt: 'List files and run tests',
options: {
permissions: [
// Allow listing files
createPermission('Bash', 'allow', { matches: { cmd: 'ls *' } }),
// Allow running tests
createPermission('Bash', 'allow', { matches: { cmd: 'npm test' } }),
// Ask for approval on sensitive files
createPermission('Read', 'ask', { matches: { path: '/etc/*' } }),
],
},
})) {
// Process messages
}权限规则支持:
* 通配符和正则表达式模式用于构建显示实时进度的用户界面:
async function executeWithProgress(prompt: string) {
console.log('Starting task...')
for await (const message of execute({ prompt })) {
if (message.type === 'system' && message.subtype === 'init') {
console.log('Tools available:', message.tools.join(', '))
} else if (message.type === 'assistant') {
// Show tool usage or assistant responses
const content = message.message.content[0]
if (content.type === 'tool_use') {
console.log(`Using ${content.name}...`)
} else if (content.type === 'text') {
console.log('Assistant:', content.text.slice(0, 100) + '...')
}
} else if (message.type === 'result') {
if (message.is_error) {
console.log('Failed:', message.error)
} else {
console.log('Completed successfully!')
console.log(message.result)
}
}
}
}优雅地处理长时间运行的操作:
async function executeWithTimeout(prompt: string, timeoutMs = 30000) {
const signal = AbortSignal.timeout(timeoutMs)
try {
for await (const message of execute({
prompt,
signal,
options: { dangerouslyAllowAll: true },
})) {
if (message.type === 'result') {
return message.result
}
}
} catch (error) {
if (error.message.includes('aborted')) {
throw new Error(`Operation timed out after ${timeoutMs}ms`)
}
throw error
}
}通过自定义工具和数据源扩展 Amp 的能力:
import { execute, type MCPConfig } from '@ampcode/sdk'
const mcpConfig: MCPConfig = {
playwright: {
command: 'npx',
args: ['-y', '@playwright/mcp@latest', '--headless'],
env: { NODE_ENV: 'production' },
},
database: {
command: 'node',
args: ['./custom-mcp-server.js'],
env: { DB_CONNECTION_STRING: process.env.DATABASE_URL },
},
}
for await (const message of execute({
prompt: 'Test the login flow on staging environment',
options: { mcpConfig, dangerouslyAllowAll: true },
})) {
if (message.type === 'system') {
console.log(
'MCP Servers:',
message.mcp_servers.map((s) => `${s.name}: ${s.status}`),
)
}
// Handle other messages...
}要了解更多关于使用 MCP 服务器扩展 Amp 的信息,请访问手册中的 MCP 配置 部分。
使用异步生成器构建流式对话:
import { execute, createUserMessage } from '@ampcode/sdk'
async function* generateMessages() {
yield createUserMessage('Start analyzing the codebase')
// Wait for some condition or user input
await new Promise((resolve) => setTimeout(resolve, 1000))
yield createUserMessage('Now focus on the authentication module')
}
for await (const message of execute({
prompt: generateMessages(),
})) {
if (message.type === 'result') {
console.log(message.result)
}
}使用设置文件(如 settings.json)配置 Amp 的行为。你可以为 Amp 提供保存在项目中的自定义设置文件:
import { execute } from '@ampcode/sdk'
// Use a custom settings file
for await (const message of execute({
prompt: 'Deploy the application',
options: {
settingsFile: './settings.json',
logLevel: 'debug',
},
})) {
// Handle messages...
}示例 settings.json创建的对话添加标签:
{
"amp.mcpServers": {
"playwright": {
"command": "npx",
"args": ["-y", "@playwright/mcp@latest", "--headless", "--isolated"]
}
},
"amp.commands.allowlist": ["npx", "node", "npm"],
"amp.tools.disable": ["web_search", "mcp__playwright__browser_resize"]
} 要查看所有可用设置,请参阅 配置设置.
通过自定义工具箱脚本扩展 Amp 的能力:
for await (const message of execute({
prompt: 'Use my custom deployment scripts',
options: {
toolbox: '/usr/repository-path/toolbox', // Path to toolbox scripts
},
})) {
// Handle messages...
}要了解更多关于 Amp 工具箱的信息,请参阅 Amp 使用手册的 工具箱 部分。
从指定目录加载自定义技能:
for await (const message of execute({
prompt: 'Use my custom deployment skill',
options: {
skills: './my-skills', // Path to custom skills directory
},
})) {
// Process messages
}要了解更多关于创建自定义技能的信息,请参阅 Amp 文档的 Agent 技能 部分。