diff --git a/docs/orchestration-v2/orchestrator-mcp-server.md b/docs/orchestration-v2/orchestrator-mcp-server.md index 5f48ed4a2c14f..f412afb3b746d 100644 --- a/docs/orchestration-v2/orchestrator-mcp-server.md +++ b/docs/orchestration-v2/orchestrator-mcp-server.md @@ -102,11 +102,17 @@ server headers or token. ### Cursor Agent SDK V2 Cursor receives the same authenticated HTTP MCP endpoint through the SDK's -`mcpServers` on `Agent.create` / `Agent.resume` and each `send`. With -`@cursor/sdk` 1.0.39+, send-level servers replace only the create-time inline -set; ambient servers from `settingSources` (`project`, `user`, `team`, `mdm`, -`plugins`) stay available. The adapter passes the authorization header to the -SDK but projects only redacted option metadata into protocol diagnostics. +`mcpServers` on `Agent.create` / `Agent.resume`, alongside `mcp.json` servers +whose `${workspaceFolder}` paths the SDK cannot start as written. Ambient servers +from `settingSources` (`project`, `user`, `team`, `mdm`, `plugins`) load with them. +Sends never carry `mcpServers`: a send that does makes the SDK reread the Cursor +MCP files and reconnect every server, ambient ones included, which respawns stdio +servers and delays the run. A live agent keeps the files it opened with, so the +adapter reads them and resolves the set on every turn, and reopens the agent when +either changes, such as a new endpoint or token, or an edit to `mcp.json` or +`mcp-disabled.json`. +The adapter passes the authorization header to the SDK but projects only redacted +option metadata into protocol diagnostics. ### Grok ACP V2 diff --git a/packages/provider-cursor/src/server/adapter.test.ts b/packages/provider-cursor/src/server/adapter.test.ts index 5c0a1940d671c..3d04f6d481438 100644 --- a/packages/provider-cursor/src/server/adapter.test.ts +++ b/packages/provider-cursor/src/server/adapter.test.ts @@ -268,7 +268,7 @@ describe("CursorAdapterV2", () => { Stream.takeUntil((event) => event.type === "turn.terminal"), Stream.runCollect, ); - assert.isTrue(sentWithMcpOverride); + assert.isFalse(sentWithMcpOverride); const rows = events.filter((event) => event.type === "subagent.updated"); assert.equal(rows[0]?.subagent.status, "running"); assert.equal(rows[0]?.subagent.model, model ?? null); @@ -761,6 +761,9 @@ describe("CursorAdapterV2", () => { const fileSystem = yield* FileSystem.FileSystem; const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-v2-device-" }); const sentMessages: Array = []; + const sentMcpOverrides: Array = []; + let opens = 0; + let openedMcpServers: ReturnType; const rewoundAfter: Array = []; let rewindFails = false; let nextRunStatus: "finished" | "error" = "finished"; @@ -769,14 +772,14 @@ describe("CursorAdapterV2", () => { const instanceId = ProviderInstanceId.make("cursor"); const threadId = ThreadId.make("cursor-device-thread"); const mcpSessions = yield* McpProviderSessions.McpProviderSessions; - const setDeviceAccess = (device: boolean) => + const setDeviceAccess = (device: boolean, token = "synthetic-cursor-token") => mcpSessions.set({ environmentId: EnvironmentId.make("cursor-device-environment"), threadId, providerSessionId: "cursor-device-session", providerInstanceId: instanceId, endpoint: "http://127.0.0.1:43123/mcp", - authorizationHeader: "Bearer synthetic-cursor-token", + authorizationHeader: `Bearer ${token}`, browserToolsAvailable: true, capabilities: new Set(device ? ["device"] : []), }); @@ -793,6 +796,8 @@ describe("CursorAdapterV2", () => { Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, { assertComplete: Effect.void, open: (openInput) => { + opens += 1; + openedMcpServers = openInput.options.mcpServers; const agentId = openInput.agentId ?? `native-cursor-device-${++createdAgents}`; return Effect.succeed({ agentId, @@ -809,6 +814,7 @@ describe("CursorAdapterV2", () => { : Effect.sync(() => void rewoundAfter.push(runId)), send: (input) => Effect.sync(() => { + sentMcpOverrides.push(Object.hasOwn(input.options ?? {}, "mcpServers")); sentMessages.push( typeof input.message === "string" ? input.message : input.message.text, ); @@ -1007,6 +1013,14 @@ describe("CursorAdapterV2", () => { yield* send(false, undefined, { model: "gemini-4-neon" }), told(false, false, false), ); + const opensBeforeRotation = opens; + yield* setDeviceAccess(true, "rotated-cursor-token"); + const rotated = yield* mcpSessions.read(threadId); + yield* send(); + yield* send(); + assert.equal(opens, opensBeforeRotation + 1, "a rotated MCP token reopens the agent once"); + assert.deepEqual(openedMcpServers, cursorMcpServers(rotated)); + assert.notInclude(sentMcpOverrides, true); const keptTurn = lastProviderTurn!; yield* send(false, undefined, { model: "gemini-4-neon" }); @@ -3155,6 +3169,7 @@ describe("CursorAdapterV2", () => { cwd, }); let openedWith: CursorAgentSdk.CursorAgentSdkOpenInput["options"] | undefined; + let opens = 0; const sentWith: Array | undefined> = []; const adapter = yield* makeCursorAdapterV2({ instanceId, @@ -3169,6 +3184,7 @@ describe("CursorAdapterV2", () => { assertComplete: Effect.void, open: (input) => Effect.sync(() => { + opens += 1; openedWith = input.options; return { agentId: "native-cursor-mcp", @@ -3196,13 +3212,13 @@ describe("CursorAdapterV2", () => { Effect.provideService(HostProcess.Environment, {}), ); const now = yield* DateTime.now; - const sendTurn = (ordinal: number) => + const sendTurn = (ordinal: number, policy = runtimePolicy) => runtime .startTurn({ threadId, providerThread, modelSelection, - runtimePolicy, + runtimePolicy: policy, runId: RunId.make(`cursor-mcp-run-${ordinal}`), runOrdinal: ordinal, providerTurnOrdinal: ordinal, @@ -3258,31 +3274,68 @@ describe("CursorAdapterV2", () => { }, "cwd-only": { command: "node", args: ["server.mjs"], cwd: projectRoot }, }; - // The agent is created with T3's server only; the resolved servers go with each turn. - assert.deepEqual(openedWith?.mcpServers, t3Servers); + // The agent opens with the resolved servers and T3's, and keeps them while they are unchanged. + assert.deepEqual(openedWith?.mcpServers, { ...expectedServers, ...t3Servers }); yield* sendTurn(1); - assert.deepEqual(sentWith[0], { ...expectedServers, ...t3Servers }); + assert.equal(opens, 1, "an unchanged mcp.json keeps the open agent"); + // The SDK loads the servers that are not inline from the files, so editing those reopens it. + yield* fileSystem.writeFileString( + path.join(home, ".cursor", "mcp.json"), + JSON.stringify({ mcpServers: { docs: { url: "https://docs.example/v2" } } }), + ); + yield* sendTurn(2); + yield* fileSystem.writeFileString( + path.join(home, ".cursor", "projects", projectDirectory, "mcp-disabled.json"), + JSON.stringify(["off", "plain"]), + ); + yield* sendTurn(3); + assert.deepEqual(openedWith?.mcpServers, { ...expectedServers, ...t3Servers }); + assert.equal(opens, 3, "edits to servers the files define reopen the agent"); // A server switched off between turns stays off on the next one. yield* fileSystem.writeFileString( path.join(home, ".cursor", "projects", projectDirectory, "mcp-disabled.json"), JSON.stringify(["off", "repro"]), ); - yield* sendTurn(2); + yield* sendTurn(4); const { repro: _disabled, ...stillEnabled } = expectedServers; - assert.deepEqual(sentWith[1], { ...stillEnabled, ...t3Servers }); + assert.deepEqual(openedWith?.mcpServers, { ...stillEnabled, ...t3Servers }); // Unreadable disabled state starts none of the overrides, and the turn still goes out. yield* fileSystem.writeFileString( path.join(home, ".cursor", "projects", projectDirectory, "mcp-disabled.json"), "[", ); - yield* sendTurn(3); - assert.deepEqual(sentWith[2], t3Servers); + yield* sendTurn(5); + assert.deepEqual(openedWith?.mcpServers, t3Servers); + assert.equal(opens, 5, "each change to the servers or files reopens the agent once"); + // Without a cwd the SDK works in the server's directory, and still reads the user mcp.json. + const noCwdPolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: null, + }); + yield* sendTurn(6, noCwdPolicy); + yield* sendTurn(7, noCwdPolicy); + assert.equal( + opens, + 6, + "an agent without a cwd reopens for the files it reads, then stays open", + ); + yield* fileSystem.writeFileString( + path.join(home, ".cursor", "mcp.json"), + JSON.stringify({ mcpServers: { docs: { url: "https://docs.example/v3" } } }), + ); + yield* sendTurn(8, noCwdPolicy); + assert.equal(opens, 7, "an edited mcp.json reopens an agent without a cwd"); + assert.deepEqual( + sentWith, + Array.from({ length: 8 }, () => undefined), + ); yield* fileSystem.writeFileString( path.join(workspace, ".cursor", "mcp.json"), JSON.stringify({ mcpServers: { plain: { command: "node", args: ["server.mjs"] } } }), ); yield* fileSystem.remove(path.join(home, ".cursor", "mcp.json")); - assert.deepEqual(yield* loadServers(), {}); + assert.deepEqual((yield* loadServers()).servers, {}); }).pipe( Effect.scoped, Effect.provide( diff --git a/packages/provider-cursor/src/server/adapter.ts b/packages/provider-cursor/src/server/adapter.ts index 0ff95908833cb..3615f9b55b56c 100644 --- a/packages/provider-cursor/src/server/adapter.ts +++ b/packages/provider-cursor/src/server/adapter.ts @@ -35,6 +35,7 @@ import { import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Equal from "effect/Equal"; import * as FileSystem from "effect/FileSystem"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; @@ -59,7 +60,7 @@ import { hasCursorSkillMention, rewriteCursorSkillMentions, } from "./skills.ts"; -import { cursorWorkspaceMcpServers } from "./workspaceMcpServers.ts"; +import { cursorWorkspaceMcpServers, type CursorWorkspaceMcp } from "./workspaceMcpServers.ts"; import { t3OrchestrationPrompt } from "@t3tools/provider-core/server/orchestrationInstructions"; import { buildRuntimeInstructions } from "@t3tools/provider-core/server/runtimeInstructions"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; @@ -309,6 +310,8 @@ const CURSOR_AGENT_SETTING_SOURCES = [ "plugins", ] as const satisfies ReadonlyArray; +const NO_WORKSPACE_MCP: CursorWorkspaceMcp = { servers: {}, configFiles: [] }; + export function makeCursorAgentOptions(input: { readonly apiKey?: string; readonly modelSelection: ModelSelection; @@ -317,10 +320,11 @@ export function makeCursorAgentOptions(input: { readonly runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy; readonly threadId: ThreadId; readonly mcpSession: McpProviderSession.McpProviderSessionConfig | undefined; + readonly workspaceMcpServers?: Record; readonly platform: NodeJS.Platform; }): AgentOptions { const policy = cursorRuntimeAgentPolicy(input.runtimePolicy, input.platform); - const mcpServers = cursorMcpServers(input.mcpSession); + const mcpServers = { ...input.workspaceMcpServers, ...cursorMcpServers(input.mcpSession) }; return { model: cursorSdkModelSelection(input.modelSelection, input.models, input.sdkModels), name: `T3 Code ${input.threadId}`, @@ -340,7 +344,7 @@ export function makeCursorAgentOptions(input: { }, enableAgentRetries: true, }, - ...(mcpServers === undefined ? {} : { mcpServers }), + ...(Object.keys(mcpServers).length === 0 ? {} : { mcpServers }), }; } @@ -1038,6 +1042,8 @@ interface CursorLiveAgent { readonly nativeThreadId: string; readonly storeCwd: string; readonly session: CursorAgentSdk.CursorAgentSdkSession; + readonly mcpServers: Record | undefined; + readonly mcpConfigFiles: CursorWorkspaceMcp["configFiles"]; } export interface CursorAdapterV2Options { @@ -2695,21 +2701,19 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( } }; - const resolveWorkspaceMcpServers = (cwd: string | null) => - cwd === null - ? Effect.succeed({}) - : cursorWorkspaceMcpServers(cwd, adapterOptions.environment).pipe( - Effect.provideService(FileSystem.FileSystem, fileSystem), - Effect.provideService(Path.Path, path), - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), - // Unreadable Cursor state leaves startup to the SDK rather than failing the turn. - Effect.catch((cause) => - Effect.logWarning("orchestration-v2.cursor-workspace-mcp-unresolved", { - cwd, - cause, - }).pipe(Effect.as({})), - ), - ); + const resolveWorkspaceMcp = (cwd: string) => + cursorWorkspaceMcpServers(cwd, adapterOptions.environment).pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + // Unreadable Cursor state leaves startup to the SDK rather than failing the turn. + Effect.catch((cause) => + Effect.logWarning("orchestration-v2.cursor-workspace-mcp-unresolved", { + cwd, + cause, + }).pipe(Effect.as(NO_WORKSPACE_MCP)), + ), + ); const openAgent = Effect.fnUntraced(function* (openInput: { readonly operation: "create" | "resume"; @@ -2729,11 +2733,30 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( : input.resumeFromSession?.cwd : undefined) ?? cwd; + // Without a cwd the SDK works in, and reads the Cursor MCP files from, process.cwd(). + const workspaceMcp = yield* resolveWorkspaceMcp(cwd); + const options = makeCursorAgentOptions({ + ...(apiKey === undefined ? {} : { apiKey }), + modelSelection: openInput.modelSelection, + models: adapterOptions.getModels?.() ?? [], + sdkModels: adapterOptions.getSdkModels?.() ?? [], + runtimePolicy: openInput.runtimePolicy, + platform, + threadId: openInput.threadId, + mcpSession: yield* mcpSessions.read(openInput.threadId), + workspaceMcpServers: workspaceMcp.servers, + }); + // A send that carries mcpServers makes the SDK reread the Cursor MCP files and reconnect + // every server, ambient ones included. A live agent keeps the files it opened with, so it + // is reopened instead when its servers or those files change: a reissued T3 token, or an + // edit to mcp.json or mcp-disabled.json, which are read again on every open. if ( existing !== null && openInput.operation === "resume" && existing.nativeThreadId === openInput.agentId && - existing.session.isAlive?.() !== false + existing.session.isAlive?.() !== false && + Equal.equals(existing.mcpServers, options.mcpServers) && + Equal.equals(existing.mcpConfigFiles, workspaceMcp.configFiles) ) { return existing; } @@ -2741,16 +2764,6 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( yield* existing.session.close.pipe(Effect.ignore); yield* Ref.set(liveAgent, null); } - const options = makeCursorAgentOptions({ - ...(apiKey === undefined ? {} : { apiKey }), - modelSelection: openInput.modelSelection, - models: adapterOptions.getModels?.() ?? [], - sdkModels: adapterOptions.getSdkModels?.() ?? [], - runtimePolicy: openInput.runtimePolicy, - platform, - threadId: openInput.threadId, - mcpSession: yield* mcpSessions.read(openInput.threadId), - }); if ( platform === "win32" && openInput.runtimePolicy.sandboxPolicy === undefined && @@ -2776,6 +2789,8 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( nativeThreadId: sdkSession.agentId, storeCwd, session: sdkSession, + mcpServers: options.mcpServers, + mcpConfigFiles: workspaceMcp.configFiles, } satisfies CursorLiveAgent; yield* Ref.set(liveAgent, next); return next; @@ -2989,12 +3004,6 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( const compacted = resume === undefined && prompt === undefined; const pendingUpdates: Array = []; let context: ActiveCursorTurn | null = null; - // A send-time set replaces the create-time set, so the workspace servers go only here and are - // read again each turn from mcp.json and mcp-disabled.json; both merge with settingSources. - const turnMcpServers = { - ...(yield* resolveWorkspaceMcpServers(turnInput.runtimePolicy.cwd)), - ...mcpServers, - }; const sdkRun = yield* agent.session .send({ message, @@ -3007,9 +3016,6 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( adapterOptions.getSdkModels?.() ?? [], ), mode: turnInput.runtimePolicy.interactionMode === "plan" ? "plan" : "agent", - ...(Object.keys(turnMcpServers).length === 0 - ? {} - : { mcpServers: turnMcpServers }), }, onDelta: (update) => { if (context === null) { diff --git a/packages/provider-cursor/src/server/workspaceMcpServers.ts b/packages/provider-cursor/src/server/workspaceMcpServers.ts index f3e53b508e3b3..0167d6b4be971 100644 --- a/packages/provider-cursor/src/server/workspaceMcpServers.ts +++ b/packages/provider-cursor/src/server/workspaceMcpServers.ts @@ -80,6 +80,13 @@ function cursorProjectSlug(projectRoot: string): string { .replace(/^-+|-+$/g, ""); } +/** The servers T3 Code passes inline, and the Cursor MCP files read to find them. */ +export interface CursorWorkspaceMcp { + readonly servers: Record; + /** `mcp-disabled.json` as text, then the project and user `mcp.json` as parsed. */ + readonly configFiles: ReadonlyArray; +} + export const cursorWorkspaceMcpServers = Effect.fn("cursorWorkspaceMcpServers")(function* ( cwd: string, environment: NodeJS.ProcessEnv, @@ -107,7 +114,7 @@ export const cursorWorkspaceMcpServers = Effect.fn("cursorWorkspaceMcpServers")( const projectRoot = Option.isSome(root) && root.value.code === 0 ? root.value.stdout.trim() : cwd; const userHome = yield* HostProcess.HomeDirectory; const cursorDataDirectory = hostEnvironment.CURSOR_DATA_DIR || path.join(userHome, ".cursor"); - const loadDisabled = fileSystem + const disabledFile = yield* fileSystem .readFileString( path.join( cursorDataDirectory, @@ -119,11 +126,12 @@ export const cursorWorkspaceMcpServers = Effect.fn("cursorWorkspaceMcpServers")( .pipe( Effect.catchIf( (error) => error.reason._tag === "NotFound", - () => Effect.succeed("[]"), + () => Effect.undefined, ), - Effect.flatMap(decodeDisabledServers), - Effect.map((names) => new Set(names)), ); + const loadDisabled = decodeDisabledServers(disabledFile ?? "[]").pipe( + Effect.map((names) => new Set(names)), + ); let disabled: Set | undefined; const variables = new Map([ ["workspaceFolder", projectRoot], @@ -143,11 +151,13 @@ export const cursorWorkspaceMcpServers = Effect.fn("cursorWorkspaceMcpServers")( const seen = new Set(); const servers: Record = {}; + const configFiles: Array = [disabledFile]; for (const file of [ path.join(projectRoot, ".cursor", "mcp.json"), path.join(userHome, ".cursor", "mcp.json"), ]) { const contents = yield* readJsonc(file); + configFiles.push(contents); // Like the SDK, expand before validating, so `"type": "${env:TYPE}"` is valid. const config = decodeCursorMcpFile(expand(contents, resolve)); if (Option.isNone(config)) continue; @@ -171,5 +181,5 @@ export const cursorWorkspaceMcpServers = Effect.fn("cursorWorkspaceMcpServers")( } } } - return servers; + return { servers, configFiles } satisfies CursorWorkspaceMcp; });