AI 编程教程中文版
官方教程中文版集成与 SDK

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 工作
调起云端并行 agentcloud runtime 可在调用方断开后继续运行
在企业环境保留代码和 secretscloud self-hosted runtime 指向自托管 pool

如果只需要 HTTP 自动化,Cloud Agents API 更直接。如果需要在应用代码里消费 stream、管理 run、接 MCP 和处理 artifacts,SDK 更合适。

2. 三种 runtime

Agent.create() 通过传入 localcloud 选择 runtime。

Runtime行为适合
Localagent inline 跑在 Node process 中,文件来自本地磁盘dev scripts、CI checks、当前 working tree
Cloud Cursor-hosted在 Cursor isolated VM 中 clone repo,Cursor 管 VM调用方没有 repo、需要并行、断线后继续跑
Cloud self-hostedAPI 形状相同,但 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.reposstartingRefautoCreatePR 等。

选项说明
model模型选择;local 通常需要显式传,cloud 可使用默认解析
local.cwd本地工作目录,可是 string 或 string[]
cloud.repos云端要 clone 的 repo
cloud.env{ type: "cloud" }{ type: "pool" }{ type: "machine" }
cloud.autoCreatePRrun 完成后自动开 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 包括 runningfinishederrorcancelled

常见 stream event:

Event type含义
systeminit metadata
user当前 run 的用户 prompt
assistant模型输出
thinkingreasoning content
tool_calltool invocation lifecycle
statuscloud run lifecycle
tasktask milestones / summaries
request等待用户输入或 approval

tool_call.argstool_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 可加载:

  1. agent.send()mcpServers,替换创建时 servers。
  2. Agent.create()mcpServers
  3. plugin servers。
  4. project .cursor/mcp.json
  5. user ~/.cursor/mcp.json

Cloud agents 可加载:

  1. agent.send()mcpServers
  2. Agent.create()mcpServers
  3. 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场景
AuthenticationErrorAPI key 无效、未登录、权限不足
RateLimitError请求过多或 usage limit 超限
ConfigurationErrormodel、参数或请求配置无效
IntegrationNotConnectedErrorcloud 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。

官方来源

接下来去哪

本页目录