Skip to content

Commit cc97303

Browse files
only21milmaria-rcksjuliusmarminge
authored
fix(cursor): mcp.json servers using ${workspaceFolder} now start (#24505)
Co-authored-by: maria-rcks <[email protected]> Co-authored-by: Julius Marminge <[email protected]>
1 parent de77e61 commit cc97303

6 files changed

Lines changed: 445 additions & 2 deletions

File tree

‎apps/server/vite.config.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,8 @@ export default mergeConfig(
115115
},
116116
}
117117
: {}),
118+
// jsonc-parser's UMD main requires its own files at runtime, which the bundle cannot follow.
119+
alias: { "jsonc-parser": "jsonc-parser/lib/esm/main.js" },
118120
deps: {
119121
// alwaysBundle=false has no opinion; neverBundle must retain transitive native acceleration.
120122
alwaysBundle: shouldBundleCliDependency,

‎packages/provider-cursor/package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@
5050
"@t3tools/provider-core": "workspace:*",
5151
"@t3tools/shared": "workspace:*",
5252
"effect": "catalog:",
53+
"jsonc-parser": "3.3.1",
5354
"yaml": "catalog:"
5455
},
5556
"devDependencies": {

‎packages/provider-cursor/src/server/adapter.test.ts‎

Lines changed: 235 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,13 +21,17 @@ import * as DateTime from "effect/DateTime";
2121
import * as Deferred from "effect/Deferred";
2222
import * as Effect from "effect/Effect";
2323
import * as Exit from "effect/Exit";
24+
import * as ChildProcess from "effect/process/ChildProcess";
25+
import { spawnAndCollect } from "@t3tools/provider-core/server/snapshotProbe";
26+
import * as HostProcess from "@t3tools/shared/HostProcess";
2427
import * as FileSystem from "effect/FileSystem";
2528
import * as Layer from "effect/Layer";
2629
import * as Option from "effect/Option";
2730
import * as Path from "effect/Path";
2831
import * as Stream from "effect/Stream";
2932
import { vi } from "vite-plus/test";
3033

34+
import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
3135
import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost";
3236
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
3337
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
@@ -42,6 +46,7 @@ import {
4246
} from "./adapter.ts";
4347
import * as CursorAgentSdk from "./CursorAgentSdk.ts";
4448
import { loadCursorSdk } from "./sdk.ts";
49+
import { cursorWorkspaceMcpServers } from "./workspaceMcpServers.ts";
4550

4651
// The SDK reads CURSOR_BACKEND_URL once when it loads, before any test body runs.
4752
const cursorBackendUrl = await vi.hoisted(async () => {
@@ -2034,6 +2039,236 @@ describe("CursorAdapterV2", () => {
20342039
assert.notInclude(logged, "secret-cursor-mcp-token");
20352040
});
20362041

2042+
it.effect.skipIf(!symlinksSupported)(
2043+
"starts mcp.json servers that use Cursor's workspace variables",
2044+
() =>
2045+
Effect.gen(function* () {
2046+
const fileSystem = yield* FileSystem.FileSystem;
2047+
const path = yield* Path.Path;
2048+
const scratch = yield* fileSystem.realPath(
2049+
yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-v2-mcp-" }),
2050+
);
2051+
const workspace = path.join(scratch, "workspace");
2052+
const home = path.join(scratch, "home");
2053+
const loadServers = () =>
2054+
cursorWorkspaceMcpServers(cwd, { MCP_TYPE: "stdio" }).pipe(
2055+
Effect.provideService(HostProcess.HomeDirectory, home),
2056+
Effect.provideService(HostProcess.Environment, {}),
2057+
);
2058+
// Cursor resolves the project root through symlinks, as git does.
2059+
yield* fileSystem.makeDirectory(path.join(workspace, "packages", "app"), {
2060+
recursive: true,
2061+
});
2062+
yield* fileSystem.symlink(workspace, path.join(scratch, "link"));
2063+
const cwd = path.join(scratch, "link", "packages", "app");
2064+
yield* spawnAndCollect("git", ChildProcess.make("git", ["init", workspace]));
2065+
// Git prints forward slashes on Windows, and the loader passes its spelling through.
2066+
const projectRoot = (yield* spawnAndCollect(
2067+
"git",
2068+
ChildProcess.make("git", ["rev-parse", "--show-toplevel"], { cwd }),
2069+
)).stdout.trim();
2070+
yield* fileSystem.makeDirectory(path.join(workspace, ".cursor"), { recursive: true });
2071+
yield* fileSystem.makeDirectory(path.join(home, ".cursor"), { recursive: true });
2072+
yield* fileSystem.writeFileString(
2073+
path.join(workspace, ".cursor", "mcp.json"),
2074+
`{
2075+
// Cursor's editor accepts comments here.
2076+
"mcpServers": {
2077+
"repro": { "command": "node", "args": ["\${workspaceFolder}/server.mjs"], "startupTimeoutSec": 120 },
2078+
"plain": { "command": "node", "args": ["server.mjs"] },
2079+
"argument-only": { "command": "node", "args": ["server.mjs", "--workspace", "\${workspaceFolder}"] },
2080+
"env-only": { "command": "node", "args": ["server.mjs"], "env": { "PROJECT_ROOT": "\${workspaceFolder}" } },
2081+
"cwd-only": { "command": "node", "args": ["server.mjs"], "cwd": "\${workspaceFolder}" },
2082+
"unset-env": { "command": "node", "env": { "CONFIG": "\${env:T3_MCP_UNSET}" } },
2083+
"wrapped": { "command": "proto", "args": ["run", "node", "--", "\${workspaceFolder}/server.mjs"] },
2084+
"label": { "command": "node", "args": ["server.mjs", "--label", "\${workspaceFolder}/client"] },
2085+
"env-file": { "command": "node", "args": ["\${workspaceFolder}/server.mjs"], "envFile": ".env.mcp" },
2086+
"tool-filter": { "command": "node", "args": ["\${workspaceFolder}/server.mjs"], "enabledTools": ["read_file"] },
2087+
"off": { "command": "node", "args": ["\${workspaceFolder}/off.mjs"] },
2088+
"typed": { "type": "\${env:MCP_TYPE}", "command": "node", "args": ["server.mjs"] },
2089+
"plugin-docs-search": { "command": "node", "args": ["\${workspaceFolder}/search.mjs"] },
2090+
},
2091+
}`,
2092+
);
2093+
yield* fileSystem.writeFileString(
2094+
path.join(home, ".cursor", "mcp.json"),
2095+
JSON.stringify({
2096+
mcpServers: {
2097+
repro: { command: "node", args: ["${userHome}/shadowed.mjs"] },
2098+
docs: {
2099+
url: "https://docs.example/${workspaceFolderBasename}",
2100+
headers: { Authorization: "Bearer ${env:DOCS_TOKEN}" },
2101+
tls: { caBundle: "${userHome}/ca.pem" },
2102+
},
2103+
},
2104+
}),
2105+
);
2106+
// Cursor keeps per-project state under a directory named after the project path.
2107+
const projectDirectory = workspace.replace(/[^a-zA-Z0-9]+/g, "-").replace(/^-|-$/g, "");
2108+
yield* fileSystem.makeDirectory(path.join(home, ".cursor", "projects", projectDirectory), {
2109+
recursive: true,
2110+
});
2111+
yield* fileSystem.writeFileString(
2112+
path.join(home, ".cursor", "projects", projectDirectory, "mcp-disabled.json"),
2113+
JSON.stringify(["off"]),
2114+
);
2115+
2116+
const instanceId = ProviderInstanceId.make("cursor");
2117+
const threadId = ThreadId.make("cursor-mcp-thread");
2118+
const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
2119+
yield* mcpSessions.set({
2120+
environmentId: EnvironmentId.make("cursor-mcp-environment"),
2121+
threadId,
2122+
providerSessionId: "cursor-mcp-session",
2123+
providerInstanceId: instanceId,
2124+
endpoint: "http://127.0.0.1:43123/mcp",
2125+
authorizationHeader: "Bearer synthetic-cursor-token",
2126+
browserToolsAvailable: false,
2127+
});
2128+
const t3Servers = cursorMcpServers(yield* mcpSessions.read(threadId));
2129+
const modelSelection = { instanceId, model: "composer-2.5" };
2130+
const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
2131+
runtimeMode: "full-access",
2132+
interactionMode: "default",
2133+
cwd,
2134+
});
2135+
let openedWith: CursorAgentSdk.CursorAgentSdkOpenInput["options"] | undefined;
2136+
const sentWith: Array<Record<string, unknown> | undefined> = [];
2137+
const adapter = yield* makeCursorAdapterV2({
2138+
instanceId,
2139+
environment: {
2140+
HOME: path.join(scratch, "override"),
2141+
CURSOR_DATA_DIR: path.join(scratch, "override"),
2142+
DOCS_TOKEN: "docs-token",
2143+
MCP_TYPE: "stdio",
2144+
},
2145+
}).pipe(
2146+
Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, {
2147+
assertComplete: Effect.void,
2148+
open: (input) =>
2149+
Effect.sync(() => {
2150+
openedWith = input.options;
2151+
return {
2152+
agentId: "native-cursor-mcp",
2153+
listMessages: Effect.succeed([]),
2154+
close: Effect.void,
2155+
send: (sendInput) => {
2156+
sentWith.push(sendInput.options?.mcpServers);
2157+
return Effect.die("sent");
2158+
},
2159+
};
2160+
}),
2161+
}),
2162+
Effect.provide(TestProviderHost.layer({ cwd })),
2163+
);
2164+
const runtime = yield* adapter.openSession({
2165+
threadId,
2166+
providerSessionId: ProviderSessionId.make("cursor-mcp-session"),
2167+
modelSelection,
2168+
runtimePolicy,
2169+
});
2170+
const providerThread = yield* runtime
2171+
.ensureThread({ threadId, modelSelection, runtimePolicy })
2172+
.pipe(
2173+
Effect.provideService(HostProcess.HomeDirectory, home),
2174+
Effect.provideService(HostProcess.Environment, {}),
2175+
);
2176+
const now = yield* DateTime.now;
2177+
const sendTurn = (ordinal: number) =>
2178+
runtime
2179+
.startTurn({
2180+
threadId,
2181+
providerThread,
2182+
modelSelection,
2183+
runtimePolicy,
2184+
runId: RunId.make(`cursor-mcp-run-${ordinal}`),
2185+
runOrdinal: ordinal,
2186+
providerTurnOrdinal: ordinal,
2187+
attemptId: RunAttemptId.make(`cursor-mcp-attempt-${ordinal}`),
2188+
rootNodeId: NodeId.make(`cursor-mcp-root-${ordinal}`),
2189+
appThread: {
2190+
id: threadId,
2191+
projectId: ProjectId.make("cursor-mcp-project"),
2192+
createdBy: "user",
2193+
creationSource: "web",
2194+
title: "Cursor MCP",
2195+
providerInstanceId: instanceId,
2196+
modelSelection,
2197+
runtimeMode: "full-access",
2198+
interactionMode: "default",
2199+
branch: null,
2200+
worktreePath: null,
2201+
activeProviderThreadId: providerThread.id,
2202+
lineage: {
2203+
parentThreadId: null,
2204+
relationshipToParent: null,
2205+
rootThreadId: threadId,
2206+
},
2207+
forkedFrom: null,
2208+
createdAt: now,
2209+
updatedAt: now,
2210+
archivedAt: null,
2211+
settledOverride: null,
2212+
settledAt: null,
2213+
lastVisitedAt: null,
2214+
deletedAt: null,
2215+
},
2216+
message: {
2217+
messageId: MessageId.make(`cursor-mcp-message-${ordinal}`),
2218+
createdBy: "user",
2219+
creationSource: "web",
2220+
text: "Hello.",
2221+
attachments: [],
2222+
},
2223+
})
2224+
.pipe(
2225+
Effect.exit,
2226+
Effect.provideService(HostProcess.HomeDirectory, home),
2227+
Effect.provideService(HostProcess.Environment, {}),
2228+
);
2229+
2230+
const expectedServers = {
2231+
repro: {
2232+
command: "node",
2233+
args: [`${projectRoot}/server.mjs`],
2234+
startupTimeoutSec: 120,
2235+
cwd: projectRoot,
2236+
},
2237+
"cwd-only": { command: "node", args: ["server.mjs"], cwd: projectRoot },
2238+
};
2239+
// The agent is created with T3's server only; the resolved servers go with each turn.
2240+
assert.deepEqual(openedWith?.mcpServers, t3Servers);
2241+
yield* sendTurn(1);
2242+
assert.deepEqual(sentWith[0], { ...expectedServers, ...t3Servers });
2243+
// A server switched off between turns stays off on the next one.
2244+
yield* fileSystem.writeFileString(
2245+
path.join(home, ".cursor", "projects", projectDirectory, "mcp-disabled.json"),
2246+
JSON.stringify(["off", "repro"]),
2247+
);
2248+
yield* sendTurn(2);
2249+
const { repro: _disabled, ...stillEnabled } = expectedServers;
2250+
assert.deepEqual(sentWith[1], { ...stillEnabled, ...t3Servers });
2251+
// Unreadable disabled state starts none of the overrides, and the turn still goes out.
2252+
yield* fileSystem.writeFileString(
2253+
path.join(home, ".cursor", "projects", projectDirectory, "mcp-disabled.json"),
2254+
"[",
2255+
);
2256+
yield* sendTurn(3);
2257+
assert.deepEqual(sentWith[2], t3Servers);
2258+
yield* fileSystem.writeFileString(
2259+
path.join(workspace, ".cursor", "mcp.json"),
2260+
JSON.stringify({ mcpServers: { plain: { command: "node", args: ["server.mjs"] } } }),
2261+
);
2262+
yield* fileSystem.remove(path.join(home, ".cursor", "mcp.json"));
2263+
assert.deepEqual(yield* loadServers(), {});
2264+
}).pipe(
2265+
Effect.scoped,
2266+
Effect.provide(
2267+
Layer.mergeAll(NodeServices.layer, IdAllocator.layer, McpProviderSessions.layer),
2268+
),
2269+
),
2270+
);
2271+
20372272
it("recognizes direct and SDK-wrapped abort failures as cancellation", () => {
20382273
assert.isTrue(CursorAgentSdk.isCursorCancellationError({ name: "AbortError" }));
20392274
assert.isTrue(

‎packages/provider-cursor/src/server/adapter.ts‎

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ import * as Effect from "effect/Effect";
3737
import * as FileSystem from "effect/FileSystem";
3838
import * as Option from "effect/Option";
3939
import * as Path from "effect/Path";
40+
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
4041
import * as Queue from "effect/Queue";
4142
import * as Ref from "effect/Ref";
4243
import * as Schema from "effect/Schema";
@@ -55,6 +56,7 @@ import {
5556
hasCursorSkillMention,
5657
rewriteCursorSkillMentions,
5758
} from "./skills.ts";
59+
import { cursorWorkspaceMcpServers } from "./workspaceMcpServers.ts";
5860
import { t3OrchestrationPrompt } from "@t3tools/provider-core/server/orchestrationInstructions";
5961
import { buildRuntimeInstructions } from "@t3tools/provider-core/server/runtimeInstructions";
6062
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
@@ -979,6 +981,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
979981
options: CursorAdapterV2Options,
980982
) {
981983
const fileSystem = yield* FileSystem.FileSystem;
984+
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
982985
const path = yield* Path.Path;
983986
const idAllocator = yield* IdAllocator.IdAllocatorV2;
984987
const runner = yield* CursorAgentSdk.CursorAgentSdkRunner;
@@ -2245,6 +2248,22 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
22452248
}
22462249
};
22472250

2251+
const resolveWorkspaceMcpServers = (cwd: string | null) =>
2252+
cwd === null
2253+
? Effect.succeed({})
2254+
: cursorWorkspaceMcpServers(cwd, adapterOptions.environment).pipe(
2255+
Effect.provideService(FileSystem.FileSystem, fileSystem),
2256+
Effect.provideService(Path.Path, path),
2257+
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
2258+
// Unreadable Cursor state leaves startup to the SDK rather than failing the turn.
2259+
Effect.catch((cause) =>
2260+
Effect.logWarning("orchestration-v2.cursor-workspace-mcp-unresolved", {
2261+
cwd,
2262+
cause,
2263+
}).pipe(Effect.as({})),
2264+
),
2265+
);
2266+
22482267
const openAgent = Effect.fnUntraced(function* (openInput: {
22492268
readonly operation: "create" | "resume";
22502269
readonly threadId: ThreadId;
@@ -2456,15 +2475,22 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
24562475
const compacted = prompt === undefined;
24572476
const pendingUpdates: Array<InteractionUpdate> = [];
24582477
let context: ActiveCursorTurn | null = null;
2459-
// Create-time and send-time mcpServers merge with settingSources (SDK >= 1.0.39).
2478+
// A send-time set replaces the create-time set, so the workspace servers go only here and are
2479+
// read again each turn from mcp.json and mcp-disabled.json; both merge with settingSources.
2480+
const turnMcpServers = {
2481+
...(yield* resolveWorkspaceMcpServers(turnInput.runtimePolicy.cwd)),
2482+
...mcpServers,
2483+
};
24602484
const sdkRun = yield* agent.session
24612485
.send({
24622486
message,
24632487
summarize: compacted,
24642488
options: {
24652489
model: cursorSdkModelSelection(turnInput.modelSelection),
24662490
mode: turnInput.runtimePolicy.interactionMode === "plan" ? "plan" : "agent",
2467-
...(mcpServers === undefined ? {} : { mcpServers }),
2491+
...(Object.keys(turnMcpServers).length === 0
2492+
? {}
2493+
: { mcpServers: turnMcpServers }),
24682494
},
24692495
onDelta: (update) => {
24702496
if (context === null) {
@@ -2961,6 +2987,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
29612987

29622988
export type CursorAdapterV2DriverEnv =
29632989
| CursorAgentSdk.CursorAgentSdkRunner
2990+
| ChildProcessSpawner.ChildProcessSpawner
29642991
| FileSystem.FileSystem
29652992
| Path.Path
29662993
| IdAllocator.IdAllocatorV2

0 commit comments

Comments
 (0)