· SDK 文档

概述

Amp SDK 允许你在 TypeScript 程序中代码式用使 Amp 代理。

为什么使用 Amp SDK?

Amp SDK 推供下列功能:

  • 流式输入:逐条向 Amp 代理发送消息
  • 流式输出:在代理运行时接收结构化 JSON 响应(system、assistant、result)
  • 多轮对话:跨多次推理调用保持往返交互
  • 对话连续性:继续现有对话(最新或按 ID)以构建有状态的代理工作流
  • 程序式设置:配置工作目录、设置和工具,无需用户提示——非常适合自动化
  • MCP 集成:指定给定会话中可用的 MCP 服务器
  • 自定义技能:定义和使用自定义代理技能以扩展 Amp 的功能

你可以构建什么?

以下是使用 Amp SDK 可以构建的一些示例:

开发工具

  • 代码审格代理:自动化 Pull Request 分析和反馈
  • 文档生成器:创建和维护项目文档
  • 测试自动化:生成和执行测试套件
  • 轉換帮助:帮助升级代码库和重构遗留代码

工作流转自动化

  • CI/CD 集成:智能构建和部署流水线
  • 问题分类:自动分类和优先级排序 Bug 报告
  • 代码较量监控:持续分析代码健康指标
  • 发布管理:自动生成变更日志和版本升级

限制

  • Amp SDK 仅消耗付费额度。Amp Free 仅适用于交互式 Amp 使用。

快速开始

安装

# 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.

运行你的第一个 Amp 命令

现在你已经安装了 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 模式

选择要使用的 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
	}
}

MCP 集成

通过自定义工具和数据源扩展 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 技能 部分。