TypeScript SDK
基于 Cursor 官方 TypeScript SDK 文档解释 local/cloud runtimes、Agent/Run、streaming、MCP、subagents、hooks、artifacts 和 errors。
@cursor/sdk 让你可以从 TypeScript 代码里调用 Cursor agent。官方当前标记为 public beta,GA 前 API 可能变化。
阅读目标:读完本章,你应该能判断什么时候用 SDK 而不是 CLI/API,并能看懂 Agent、Run、runtime、stream、MCP 和 resource management 的核心关系。
1. SDK 适合什么
SDK 把 Cursor IDE、CLI、Web app 背后的同一类 agent 变成可编程接口。
| 需求 | SDK 价值 |
|---|---|
| 在内部平台发起 agent 任务 | 用 TypeScript 直接创建 agent 和 run |
| 在 CI 或 dev script 中跑 agent 检查 | local runtime 直接对 working tree 工作 |
| 调起云端并行 agent | cloud runtime 可在调用方断开后继续运行 |
| 在企业环境保留代码和 secrets | cloud self-hosted runtime 指向自托管 pool |
如果只需要 HTTP 自动化,Cloud Agents API 更直接。如果需要在应用代码里消费 stream、管理 run、接 MCP 和处理 artifacts,SDK 更合适。
2. 三种 runtime
Agent.create() 通过传入 local 或 cloud 选择 runtime。
| Runtime | 行为 | 适合 |
|---|---|---|
| Local | agent inline 跑在 Node process 中,文件来自本地磁盘 | dev scripts、CI checks、当前 working tree |
| Cloud Cursor-hosted | 在 Cursor isolated VM 中 clone repo,Cursor 管 VM | 调用方没有 repo、需要并行、断线后继续跑 |
| Cloud self-hosted | API 形状相同,但 VM 由 self-hosted pool 提供 | 代码、secrets、build artifacts 要留在企业环境 |
同一个 CURSOR_API_KEY 可用于 local 或 cloud。API key 可来自用户,也可来自 service account;Team Admin API keys 官方当前不支持。
3. 核心概念
| Concept | 含义 |
|---|---|
| Agent | 持久容器,保存 conversation state、workspace config 和 settings |
| Run | 一次 prompt submission,拥有自己的 stream、status、result 和 cancellation |
| SDKMessage | 标准化 stream event,跨 runtime 保持同一 envelope |
Agent 可以跨多个 prompt 保留上下文。Run 是每次执行的单位。不要把 Agent 和 Run 混成一个对象。
4. 安装和认证
安装包:
npm install @cursor/sdk
认证方式:
| 方式 | 用途 |
|---|---|
CURSOR_API_KEY environment variable | 默认推荐,避免硬编码 |
apiKey option | 脚本或平台注入 key |
| User API key | 从 Cursor Dashboard -> Integrations 生成 |
| Service account API key | 从 Team settings 创建,适合自动化 |
SDK runs 遵循 IDE 和 Cloud Agents 相同的 pricing、request pools 和 Privacy Mode 规则。usage dashboard 中会以 SDK tag 展示。
5. 创建 Agent
创建 local agent 时传 local.cwd。创建 cloud agent 时传 cloud.repos、startingRef、autoCreatePR 等。
| 选项 | 说明 |
|---|---|
model | 模型选择;local 通常需要显式传,cloud 可使用默认解析 |
local.cwd | 本地工作目录,可是 string 或 string[] |
cloud.repos | 云端要 clone 的 repo |
cloud.env | { type: "cloud" }、{ type: "pool" } 或 { type: "machine" } |
cloud.autoCreatePR | run 完成后自动开 PR |
cloud.workOnCurrentBranch | 推到现有 branch,而不是新 branch |
agent.agentId 创建后立即可用。local agents 使用 agent-<uuid>,cloud agents 使用 bc-<uuid>。
SDK 创建的 cloud agents 在 Cursor Web / Cursor window 默认列表中会被过滤。需要在 Filter -> Source -> SDK 中查看。
6. Cloud envVars
cloud agent 可传 cloud.envVars 注入 session-scoped values。
特点:
- 加密 at rest。
- 注入 cloud agent shell。
- 随 agent 删除而删除。
- 变量名不能以
CURSOR_开头。 - 不能和 caller-supplied
agentId一起用。
它适合短期值,不适合长期 secrets 治理。长期凭据仍应放 Cloud Agents dashboard 的 Secrets。
7. 发送消息和 stream
agent.send() 返回 Run。Run 支持:
| 方法 | 用途 |
|---|---|
stream() | async generator,读取 SDKMessage events |
wait() | 不消费 stream,等待最终结果 |
cancel() | 取消 running run |
conversation() | 读取结构化 conversation turns |
supports() | 检查当前 runtime 是否支持某操作 |
onDidChangeStatus() | 监听 status 变化 |
Run status 包括 running、finished、error、cancelled。
常见 stream event:
| Event type | 含义 |
|---|---|
system | init metadata |
user | 当前 run 的用户 prompt |
assistant | 模型输出 |
thinking | reasoning content |
tool_call | tool invocation lifecycle |
status | cloud run lifecycle |
task | task milestones / summaries |
request | 等待用户输入或 approval |
tool_call.args 和 tool_call.result schema 不稳定。要当 unknown 解析,不要依赖内部 shape。
8. Model 和 repositories
用 Cursor.models.list() 发现可用 model ids、parameters 和 preset variants。参数按模型变化,常见例子是 reasoning effort 或 max mode。
per-run model override 会变成 sticky:一次 agent.send(..., { model }) 成功后,后续 send 不传 model 会继续沿用这个新 selection。
用 Cursor.repositories.list() 列出当前用户团队通过 Cursor GitHub App 可访问的 GitHub repositories。官方说明为 cloud only。
9. MCP、subagents 和 hooks
MCP 来源按 runtime 不同。
Local agents 可加载:
agent.send()的mcpServers,替换创建时 servers。Agent.create()的mcpServers。- plugin servers。
- project
.cursor/mcp.json。 - user
~/.cursor/mcp.json。
Cloud agents 可加载:
agent.send()的mcpServers。Agent.create()的mcpServers。- cursor.com/agents 上的 user 和 team MCP servers。
HTTP headers / auth 在 cloud 中由 Cursor backend 处理,敏感字段不会进 VM。stdio env 会进入 VM,因为 server 在 VM 中运行。
Subagents 可 inline 定义,也可来自 repo 的 .cursor/agents/*.md。同名时 inline 覆盖 file-based。
Hooks 只有 file-based,没有 programmatic hook callback。local 读 .cursor/hooks.json 或 ~/.cursor/hooks.json;cloud 读 repo 中提交的 .cursor/hooks.json,Enterprise 还会运行 team 和 managed hooks。
10. Artifacts 和资源管理
cloud agents 支持 listArtifacts() 和 downloadArtifact(path)。local agents 当前返回空列表,下载会抛错。
每次用完 agent 要 dispose。推荐 await using,或显式调用 agent[Symbol.asyncDispose]()。
| 方法 | 用途 |
|---|---|
close() | fire-and-forget 开始 disposal |
reload() | 重读 filesystem config,例如 hooks、project MCP、subagents |
asyncDispose | 等待清理完成 |
不做 cleanup 的脚本容易留下长期 agent、未结束 run 或资源占用。
11. 错误和限制
SDK 错误都继承 CursorAgentError,带 isRetryable 用于 retry 判断。
常见错误:
| Error | 场景 |
|---|---|
AuthenticationError | API key 无效、未登录、权限不足 |
RateLimitError | 请求过多或 usage limit 超限 |
ConfigurationError | model、参数或请求配置无效 |
IntegrationNotConnectedError | cloud agent 的 SCM provider 未连接 |
NetworkError | 服务不可用或 timeout |
UnknownAgentError | 未分类 server / runtime 错误 |
已知限制:
- inline
mcpServers不会跨Agent.resume()持久化,resume 时要重新传。 - local agents 不支持 artifact download。
local.settingSources不适用于 cloud agents。- hooks 只能文件配置,不能用代码 callback。
商业级验收
上线 SDK 集成前至少确认:
- beta API 变化有版本监控。
- API key 类型、权限和轮换方式明确。
- local / cloud runtime 选择可解释。
- stream、wait、cancel、error、retry 都有处理。
- MCP secrets 不会以 stdio env 形式无意进入 cloud VM。
- artifacts 下载和过期策略明确。
- agent dispose 有保证。
- usage dashboard 中能追踪 SDK spend。
官方来源
- Cursor TypeScript SDK —— 官方 public beta、runtime、Agent、Run、stream、MCP、subagents、hooks、artifacts、errors 和 limitations。
- Cursor Cloud Agents API —— REST API 对照。
- Cursor MCP —— MCP 配置背景。
- Cursor Cloud Agent Capabilities —— Cloud MCP 和 artifacts 背景。