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。

官方來源

接下來去哪

本頁目錄