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 背景。