Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 11 additions & 5 deletions docs/orchestration-v2/orchestrator-mcp-server.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
79 changes: 66 additions & 13 deletions packages/provider-cursor/src/server/adapter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -761,6 +761,9 @@ describe("CursorAdapterV2", () => {
const fileSystem = yield* FileSystem.FileSystem;
const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-v2-device-" });
const sentMessages: Array<string> = [];
const sentMcpOverrides: Array<boolean> = [];
let opens = 0;
let openedMcpServers: ReturnType<typeof cursorMcpServers>;
const rewoundAfter: Array<string> = [];
let rewindFails = false;
let nextRunStatus: "finished" | "error" = "finished";
Expand All @@ -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"] : []),
});
Expand All @@ -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,
Expand All @@ -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,
);
Expand Down Expand Up @@ -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" });
Expand Down Expand Up @@ -3155,6 +3169,7 @@ describe("CursorAdapterV2", () => {
cwd,
});
let openedWith: CursorAgentSdk.CursorAgentSdkOpenInput["options"] | undefined;
let opens = 0;
const sentWith: Array<Record<string, unknown> | undefined> = [];
const adapter = yield* makeCursorAdapterV2({
instanceId,
Expand All @@ -3169,6 +3184,7 @@ describe("CursorAdapterV2", () => {
assertComplete: Effect.void,
open: (input) =>
Effect.sync(() => {
opens += 1;
openedWith = input.options;
return {
agentId: "native-cursor-mcp",
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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(
Expand Down
82 changes: 44 additions & 38 deletions packages/provider-cursor/src/server/adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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";
Expand Down Expand Up @@ -309,6 +310,8 @@ const CURSOR_AGENT_SETTING_SOURCES = [
"plugins",
] as const satisfies ReadonlyArray<SettingSource>;

const NO_WORKSPACE_MCP: CursorWorkspaceMcp = { servers: {}, configFiles: [] };

export function makeCursorAgentOptions(input: {
readonly apiKey?: string;
readonly modelSelection: ModelSelection;
Expand All @@ -317,10 +320,11 @@ export function makeCursorAgentOptions(input: {
readonly runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy;
readonly threadId: ThreadId;
readonly mcpSession: McpProviderSession.McpProviderSessionConfig | undefined;
readonly workspaceMcpServers?: Record<string, McpServerConfig>;
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}`,
Expand All @@ -340,7 +344,7 @@ export function makeCursorAgentOptions(input: {
},
enableAgentRetries: true,
},
...(mcpServers === undefined ? {} : { mcpServers }),
...(Object.keys(mcpServers).length === 0 ? {} : { mcpServers }),
};
}

Expand Down Expand Up @@ -1038,6 +1042,8 @@ interface CursorLiveAgent {
readonly nativeThreadId: string;
readonly storeCwd: string;
readonly session: CursorAgentSdk.CursorAgentSdkSession;
readonly mcpServers: Record<string, McpServerConfig> | undefined;
readonly mcpConfigFiles: CursorWorkspaceMcp["configFiles"];
}

export interface CursorAdapterV2Options {
Expand Down Expand Up @@ -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";
Expand All @@ -2729,28 +2733,37 @@ 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;
}
if (existing !== null) {
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 &&
Expand All @@ -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;
Expand Down Expand Up @@ -2989,12 +3004,6 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
const compacted = resume === undefined && prompt === undefined;
const pendingUpdates: Array<InteractionUpdate> = [];
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,
Expand All @@ -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) {
Expand Down
Loading
Loading