The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 18:30 UTC
fix(cursor): mcp.json servers using ${workspaceFolder} now start (#24505)
Co-authored-by: maria-rcks <maria@kuuro.net> Co-authored-by: Julius Marminge <julius0216@outlook.com>
Victor committed
Nov 12, 2026 at 17:23 UTC
cc973033818e630dec3c5cc14dc924bfbec7277d
6 files changed
+445
-2
apps/server/vite.config.ts
+2
@@ -115,6 +115,8 @@ export default mergeConfig(
115
},
116
}
117
: {}),
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" },
120
deps: {
121
// alwaysBundle=false has no opinion; neverBundle must retain transitive native acceleration.
122
alwaysBundle: shouldBundleCliDependency,
packages/provider-cursor/package.json
+1
@@ -50,6 +50,7 @@
50
"@t3tools/provider-core": "workspace:*",
51
"@t3tools/shared": "workspace:*",
52
"effect": "catalog:",
53
+ "jsonc-parser": "3.3.1",
54
"yaml": "catalog:"
55
},
56
"devDependencies": {
packages/provider-cursor/src/server/adapter.test.ts
+235
@@ -21,6 +21,9 @@ import * as DateTime from "effect/DateTime";
21
import * as Deferred from "effect/Deferred";
22
import * as Effect from "effect/Effect";
23
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";
27
import * as FileSystem from "effect/FileSystem";
28
import * as Layer from "effect/Layer";
29
import * as Option from "effect/Option";
@@ -28,6 +31,7 @@ import * as Path from "effect/Path";
31
import * as Stream from "effect/Stream";
32
import { vi } from "vite-plus/test";
33
34
+import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
35
import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost";
36
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
37
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
@@ -42,6 +46,7 @@ import {
46
} from "./adapter.ts";
47
import * as CursorAgentSdk from "./CursorAgentSdk.ts";
48
import { loadCursorSdk } from "./sdk.ts";
49
+import { cursorWorkspaceMcpServers } from "./workspaceMcpServers.ts";
50
51
// The SDK reads CURSOR_BACKEND_URL once when it loads, before any test body runs.
52
const cursorBackendUrl = await vi.hoisted(async () => {
@@ -2034,6 +2039,236 @@ describe("CursorAdapterV2", () => {
2039
assert.notInclude(logged, "secret-cursor-mcp-token");
2040
});
2041
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
+
2272
it("recognizes direct and SDK-wrapped abort failures as cancellation", () => {
2273
assert.isTrue(CursorAgentSdk.isCursorCancellationError({ name: "AbortError" }));
2274
assert.isTrue(
packages/provider-cursor/src/server/adapter.ts
+29
-2
@@ -37,6 +37,7 @@ import * as Effect from "effect/Effect";
37
import * as FileSystem from "effect/FileSystem";
38
import * as Option from "effect/Option";
39
import * as Path from "effect/Path";
40
+import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
41
import * as Queue from "effect/Queue";
42
import * as Ref from "effect/Ref";
43
import * as Schema from "effect/Schema";
@@ -55,6 +56,7 @@ import {
56
hasCursorSkillMention,
57
rewriteCursorSkillMentions,
58
} from "./skills.ts";
59
+import { cursorWorkspaceMcpServers } from "./workspaceMcpServers.ts";
60
import { t3OrchestrationPrompt } from "@t3tools/provider-core/server/orchestrationInstructions";
61
import { buildRuntimeInstructions } from "@t3tools/provider-core/server/runtimeInstructions";
62
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
@@ -979,6 +981,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
981
options: CursorAdapterV2Options,
982
) {
983
const fileSystem = yield* FileSystem.FileSystem;
984
+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
985
const path = yield* Path.Path;
986
const idAllocator = yield* IdAllocator.IdAllocatorV2;
987
const runner = yield* CursorAgentSdk.CursorAgentSdkRunner;
@@ -2245,6 +2248,22 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
2248
}
2249
};
2250
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
+
2267
const openAgent = Effect.fnUntraced(function* (openInput: {
2268
readonly operation: "create" | "resume";
2269
readonly threadId: ThreadId;
@@ -2456,7 +2475,12 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
2475
const compacted = prompt === undefined;
2476
const pendingUpdates: Array<InteractionUpdate> = [];
2477
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
+ };
2484
const sdkRun = yield* agent.session
2485
.send({
2486
message,
@@ -2464,7 +2488,9 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
2488
options: {
2489
model: cursorSdkModelSelection(turnInput.modelSelection),
2490
mode: turnInput.runtimePolicy.interactionMode === "plan" ? "plan" : "agent",
2467
- ...(mcpServers === undefined ? {} : { mcpServers }),
2491
+ ...(Object.keys(turnMcpServers).length === 0
2492
+ ? {}
2493
+ : { mcpServers: turnMcpServers }),
2494
},
2495
onDelta: (update) => {
2496
if (context === null) {
@@ -2961,6 +2987,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
2987
2988
export type CursorAdapterV2DriverEnv =
2989
| CursorAgentSdk.CursorAgentSdkRunner
2990
+ | ChildProcessSpawner.ChildProcessSpawner
2991
| FileSystem.FileSystem
2992
| Path.Path
2993
| IdAllocator.IdAllocatorV2
packages/provider-cursor/src/server/workspaceMcpServers.ts
new
+175
@@ -0,0 +1,175 @@
1
+// The SDK leaves editor variables literal; agent-level stdio clients take precedence.
2
+import type { McpServerConfig } from "@cursor/sdk";
3
+import * as Effect from "effect/Effect";
4
+import * as FileSystem from "effect/FileSystem";
5
+import * as Option from "effect/Option";
6
+import * as Path from "effect/Path";
7
+import * as Schema from "effect/Schema";
8
+import * as ChildProcess from "effect/process/ChildProcess";
9
+import { spawnAndCollect } from "@t3tools/provider-core/server/snapshotProbe";
10
+import { parse as parseJsonc, type ParseError } from "jsonc-parser";
11
+import * as HostProcess from "@t3tools/shared/HostProcess";
12
+
13
+// The SDK's own placeholder grammar: `${env:NAME}`, `${NAME}` and `${NAME:-default}`.
14
+const PLACEHOLDER_PATTERN = /\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g;
15
+const WORKSPACE_VARIABLE_PATTERN =
16
+ /\$\{(?:workspaceFolder|workspaceFolderBasename|userHome|pathSeparator|\/)\}/;
17
+const WORKSPACE_PATH_PATTERN = /^\$\{(?:workspaceFolder|userHome)\}[\\/]/;
18
+// These exit when their script argument is missing; other arguments may be labels a server ignores.
19
+const SCRIPT_INTERPRETERS = new Set(["node", "bun", "tsx", "python", "python3"]);
20
+
21
+const StringRecord = Schema.Record(Schema.String, Schema.String);
22
+const CursorMcpFile = Schema.Struct({
23
+ mcpServers: Schema.Record(
24
+ Schema.String,
25
+ Schema.Union([
26
+ Schema.Struct({
27
+ type: Schema.optional(Schema.Literal("stdio")),
28
+ command: Schema.String,
29
+ args: Schema.optional(Schema.Array(Schema.String)),
30
+ env: Schema.optional(StringRecord),
31
+ cwd: Schema.optional(Schema.String),
32
+ startupTimeoutSec: Schema.optional(Schema.Number),
33
+ }),
34
+ Schema.Struct({
35
+ type: Schema.optional(Schema.Literals(["http", "sse"])),
36
+ url: Schema.String,
37
+ }),
38
+ ]),
39
+ ),
40
+});
41
+const decodeCursorMcpFile = Schema.decodeUnknownOption(CursorMcpFile);
42
+const decodeDisabledServers = Schema.decodeEffect(
43
+ Schema.fromJsonString(Schema.Array(Schema.String)),
44
+);
45
+
46
+function expand<A>(value: A, resolve: (text: string) => string): A {
47
+ if (typeof value === "string") return resolve(value) as A;
48
+ if (Array.isArray(value)) return value.map((item: unknown) => expand(item, resolve)) as A;
49
+ if (typeof value === "object" && value !== null) {
50
+ return Object.fromEntries(
51
+ Object.entries(value).map(([key, item]) => [key, expand(item, resolve)]),
52
+ ) as A;
53
+ }
54
+ return value;
55
+}
56
+
57
+// Only servers whose literal copy cannot start: the SDK also starts the file-defined copy and
58
+// loses its handle when it keeps the inline one, and inline configs drop envFile and enabledTools.
59
+function needsWorkspaceExpansion(server: unknown): boolean {
60
+ if (typeof server !== "object" || server === null) return false;
61
+ if ("envFile" in server || "enabledTools" in server) return false;
62
+ const { command, cwd, args } = server as Record<string, unknown>;
63
+ return (
64
+ [command, cwd].some(
65
+ (text) => typeof text === "string" && WORKSPACE_VARIABLE_PATTERN.test(text),
66
+ ) ||
67
+ (typeof command === "string" &&
68
+ SCRIPT_INTERPRETERS.has(command.replace(/^.*[\\/]/, "").replace(/\.exe$/i, "")) &&
69
+ Array.isArray(args) &&
70
+ typeof args[0] === "string" &&
71
+ WORKSPACE_PATH_PATTERN.test(args[0]))
72
+ );
73
+}
74
+
75
+/** Cursor's project slug, as `~/.cursor/projects/<slug>` names it. */
76
+function cursorProjectSlug(projectRoot: string): string {
77
+ return projectRoot
78
+ .replace(/[^a-zA-Z0-9]/g, "-")
79
+ .replace(/-+/g, "-")
80
+ .replace(/^-+|-+$/g, "");
81
+}
82
+
83
+export const cursorWorkspaceMcpServers = Effect.fn("cursorWorkspaceMcpServers")(function* (
84
+ cwd: string,
85
+ environment: NodeJS.ProcessEnv,
86
+) {
87
+ const fileSystem = yield* FileSystem.FileSystem;
88
+ const path = yield* Path.Path;
89
+ const readJsonc = (file: string) =>
90
+ fileSystem.readFileString(file).pipe(
91
+ Effect.map((contents): unknown => {
92
+ const errors: ParseError[] = [];
93
+ const value: unknown = parseJsonc(contents, errors, { allowTrailingComma: true });
94
+ return errors.length === 0 ? value : null;
95
+ }),
96
+ Effect.catchIf(
97
+ (error) => error.reason._tag === "NotFound",
98
+ () => Effect.void,
99
+ ),
100
+ );
101
+
102
+ const hostEnvironment = yield* HostProcess.Environment;
103
+ const root = yield* spawnAndCollect(
104
+ "git",
105
+ ChildProcess.make("git", ["rev-parse", "--show-toplevel"], { cwd }),
106
+ ).pipe(Effect.option);
107
+ const projectRoot = Option.isSome(root) && root.value.code === 0 ? root.value.stdout.trim() : cwd;
108
+ const userHome = yield* HostProcess.HomeDirectory;
109
+ const cursorDataDirectory = hostEnvironment.CURSOR_DATA_DIR || path.join(userHome, ".cursor");
110
+ const loadDisabled = fileSystem
111
+ .readFileString(
112
+ path.join(
113
+ cursorDataDirectory,
114
+ "projects",
115
+ cursorProjectSlug(projectRoot),
116
+ "mcp-disabled.json",
117
+ ),
118
+ )
119
+ .pipe(
120
+ Effect.catchIf(
121
+ (error) => error.reason._tag === "NotFound",
122
+ () => Effect.succeed("[]"),
123
+ ),
124
+ Effect.flatMap(decodeDisabledServers),
125
+ Effect.map((names) => new Set(names)),
126
+ );
127
+ let disabled: Set<string> | undefined;
128
+ const variables = new Map([
129
+ ["workspaceFolder", projectRoot],
130
+ ["workspaceFolderBasename", path.basename(projectRoot)],
131
+ ["userHome", userHome],
132
+ ["pathSeparator", path.sep],
133
+ ["/", path.sep],
134
+ ]);
135
+ const resolve = (text: string) =>
136
+ text.replace(
137
+ PLACEHOLDER_PATTERN,
138
+ (match, envName: string | undefined, name: string, fallback: string | undefined) =>
139
+ (envName === undefined
140
+ ? (variables.get(name) ?? environment[name] ?? fallback)
141
+ : (environment[envName] ?? "")) ?? match,
142
+ );
143
+
144
+ const seen = new Set<string>();
145
+ const servers: Record<string, McpServerConfig> = {};
146
+ for (const file of [
147
+ path.join(projectRoot, ".cursor", "mcp.json"),
148
+ path.join(userHome, ".cursor", "mcp.json"),
149
+ ]) {
150
+ const contents = yield* readJsonc(file);
151
+ // Like the SDK, expand before validating, so `"type": "${env:TYPE}"` is valid.
152
+ const config = decodeCursorMcpFile(expand(contents, resolve));
153
+ if (Option.isNone(config)) continue;
154
+ const rawServers = (
155
+ contents as {
156
+ readonly mcpServers: Record<string, unknown>;
157
+ }
158
+ ).mcpServers;
159
+ for (const [name, server] of Object.entries(config.value.mcpServers)) {
160
+ if (seen.has(name)) continue;
161
+ seen.add(name);
162
+ // Plugin definitions take precedence in the SDK, which can see enabled plugins.
163
+ if (
164
+ "command" in server &&
165
+ !name.startsWith("plugin-") &&
166
+ needsWorkspaceExpansion(rawServers[name])
167
+ ) {
168
+ disabled ??= yield* loadDisabled;
169
+ if (disabled.has(name)) continue;
170
+ servers[name] = { ...server, cwd: server.cwd ?? projectRoot } as McpServerConfig;
171
+ }
172
+ }
173
+ }
174
+ return servers;
175
+});
pnpm-lock.yaml
+3
@@ -1743,6 +1743,9 @@ importers:
1743
effect:
1744
specifier: 4.1.3
1745
version: 4.1.3
1746
+ jsonc-parser:
1747
+ specifier: 3.3.1
1748
+ version: 3.3.1
1749
yaml:
1750
specifier: ^2.9.0
1751
version: 2.9.0