Skip to content

Commit 87e1ca7

Browse files
feat(server): MCP servers name environment variables; agents add servers without writing keys to settings.json (#45306)
1 parent 49c42d9 commit 87e1ca7

14 files changed

Lines changed: 589 additions & 44 deletions

File tree

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
import type { McpServerVariable, ResolvedMcpServer } from "@t3tools/contracts";
2+
3+
// `${NAME}` and `${NAME:-default}` as in Claude Code's .mcp.json, and `${env:NAME}` as in Cursor's.
4+
const REFERENCE = /\$\{(?:env:)?([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\}/g;
5+
6+
/**
7+
* Whether a value only names environment variables, so it holds no secret. Any other literal text
8+
* (a `:-` default, a prefix, JSON) may be one; only an auth scheme such as `Bearer ` is let through.
9+
*/
10+
export function namesEnvironmentVariables(value: string) {
11+
const matches = [...value.matchAll(REFERENCE)];
12+
if (matches.length === 0 || matches.some((match) => match[2])) return false;
13+
return /^(?:[A-Za-z]+ )?$/.test(value.replace(REFERENCE, ""));
14+
}
15+
16+
const serverValues = (server: ResolvedMcpServer): ReadonlyArray<string> =>
17+
server.transport.type === "stdio"
18+
? [
19+
server.transport.command,
20+
...server.transport.args,
21+
...server.transport.env.map((v) => v.value),
22+
]
23+
: [server.transport.url, ...server.transport.headers.map((v) => v.value)];
24+
25+
/** The environment variables the servers name, each once. */
26+
export function environmentReferenceNames(servers: ReadonlyArray<ResolvedMcpServer>) {
27+
const names = new Set<string>();
28+
for (const server of servers) {
29+
for (const value of serverValues(server)) {
30+
for (const match of value.matchAll(REFERENCE)) names.add(match[1]!);
31+
}
32+
}
33+
return [...names];
34+
}
35+
36+
/**
37+
* The servers with each reference replaced by its variable's value. A server naming a variable
38+
* that isn't set, with no default, is left out: it would start without its credential.
39+
*/
40+
export function expandEnvironmentReferences(
41+
servers: ReadonlyArray<ResolvedMcpServer>,
42+
lookup: (name: string) => string | undefined,
43+
): { readonly servers: ReadonlyArray<ResolvedMcpServer>; readonly missing: ReadonlyArray<string> } {
44+
const missing: string[] = [];
45+
const expanded = servers.flatMap((server): ReadonlyArray<ResolvedMcpServer> => {
46+
const unset = new Set<string>();
47+
const expand = (value: string) =>
48+
value.replace(REFERENCE, (_match, name: string, fallback: string | undefined) => {
49+
const variable = lookup(name);
50+
// As in a shell, a default also stands in for an empty variable.
51+
if (fallback !== undefined)
52+
return variable === undefined || variable === "" ? fallback : variable;
53+
if (variable === undefined) unset.add(name);
54+
return variable ?? "";
55+
});
56+
const variables = (list: ReadonlyArray<McpServerVariable>) =>
57+
list.map((variable) => ({ ...variable, value: expand(variable.value) }));
58+
const transport =
59+
server.transport.type === "stdio"
60+
? {
61+
...server.transport,
62+
command: expand(server.transport.command),
63+
args: server.transport.args.map(expand),
64+
env: variables(server.transport.env),
65+
}
66+
: {
67+
...server.transport,
68+
url: expand(server.transport.url),
69+
headers: variables(server.transport.headers),
70+
};
71+
if (unset.size > 0) {
72+
missing.push(...[...unset].map((name) => `${server.name} ${name}`));
73+
return [];
74+
}
75+
return [{ ...server, transport }];
76+
});
77+
return { servers: expanded, missing };
78+
}

‎apps/server/src/mcp/toolkits/environment/handlers.test.ts‎

Lines changed: 106 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ import {
44
DEFAULT_SERVER_SETTINGS,
55
EnvironmentId,
66
ProviderInstanceId,
7+
SecretRef,
8+
type ServerSettingsPatch,
79
ThreadId,
810
type OrchestrationV2ThreadShell,
911
} from "@t3tools/contracts";
@@ -18,6 +20,7 @@ import * as Environment from "../../../environment/ServerEnvironment.ts";
1820
import * as HostResources from "../../../resourceTelemetry/HostResources.ts";
1921
import * as ThreadCommandExecutor from "../../../orchestration-v2/ThreadCommandExecutor.ts";
2022
import * as ThreadManagement from "../../../orchestration-v2/ThreadManagementService.ts";
23+
import * as SecretRequests from "../../../secrets/SecretRequests.ts";
2124
import * as Settings from "../../../serverSettings.ts";
2225
import * as McpInvocationContext from "../../McpInvocationContext.ts";
2326
import * as McpToolAccess from "../../McpToolAccess.ts";
@@ -31,6 +34,8 @@ const threadId = ThreadId.make("thread:preferences");
3134
const layerEnvironment = (overrides: {
3235
readonly getThreadShell: ThreadManagement.ThreadManagementService["Service"]["getThreadShell"];
3336
readonly updateSettings?: Settings.ServerSettingsService["Service"]["updateSettings"];
37+
readonly consumeSecret?: SecretRequests.SecretRequests["Service"]["consume"];
38+
readonly settings?: typeof DEFAULT_SERVER_SETTINGS;
3439
}) =>
3540
Layer.mergeAll(
3641
ThreadCommandExecutor.layer,
@@ -59,11 +64,14 @@ const layerEnvironment = (overrides: {
5964
}),
6065
}),
6166
Layer.mock(Settings.ServerSettingsService)({
62-
getSettings: Effect.succeed(DEFAULT_SERVER_SETTINGS),
67+
getSettings: Effect.succeed(overrides.settings ?? DEFAULT_SERVER_SETTINGS),
6368
...(overrides.updateSettings === undefined
6469
? {}
6570
: { updateSettings: overrides.updateSettings }),
6671
}),
72+
Layer.mock(SecretRequests.SecretRequests)(
73+
overrides.consumeSecret === undefined ? {} : { consume: overrides.consumeSecret },
74+
),
6775
Layer.mock(HostResources.HostResources)({
6876
read: Effect.succeed({
6977
sampledAt: 0,
@@ -159,3 +167,100 @@ it("keeps agent feedback out of the preferences agents read and write", () => {
159167
Object.keys(EnvironmentToolkit.tools.t3_environment_preferences_update.parametersSchema.fields),
160168
).not.toContain("agentFeedback");
161169
});
170+
171+
it.effect("t3_mcp_server_update saves a secretRef as a secret and never shows it back", () => {
172+
const ref = SecretRef.make("secret-ref:linear");
173+
let saved: ServerSettingsPatch | undefined;
174+
return Effect.gen(function* () {
175+
const toolkit = yield* EnvironmentToolkit;
176+
const result = yield* toolkit
177+
.handle("t3_mcp_server_update", {
178+
name: "linear",
179+
server: {
180+
url: "https://mcp.linear.app/mcp",
181+
headers: {
182+
Authorization: { secretRef: ref, prefix: "Bearer " },
183+
"X-Team": "${LINEAR_TEAM}",
184+
},
185+
},
186+
})
187+
.pipe(Stream.unwrap, Stream.runCollect);
188+
189+
expect(saved?.mcpServers?.linear?.transport).toEqual({
190+
type: "http",
191+
url: "https://mcp.linear.app/mcp",
192+
headers: [
193+
{ name: "Authorization", value: "Bearer lin-secret", sensitive: true },
194+
{ name: "X-Team", value: "${LINEAR_TEAM}", sensitive: false },
195+
],
196+
});
197+
expect(result.at(-1)?.result).toEqual({
198+
servers: {
199+
linear: {
200+
enabled: true,
201+
url: "https://mcp.linear.app/mcp",
202+
headers: { Authorization: { stored: true }, "X-Team": "${LINEAR_TEAM}" },
203+
},
204+
},
205+
});
206+
}).pipe(
207+
Effect.provide(
208+
McpToolAccess.HandlersLayer.layer(EnvironmentHandlers.layer).pipe(
209+
Layer.provideMerge(
210+
layerEnvironment({
211+
getThreadShell: () => Effect.succeed(liveThreadShell(threadId)),
212+
consumeSecret: (input) =>
213+
input.ref === ref ? Effect.succeed("lin-secret") : Effect.die("unexpected secretRef"),
214+
updateSettings: (patch) =>
215+
Effect.sync(() => {
216+
saved = patch;
217+
return {
218+
...DEFAULT_SERVER_SETTINGS,
219+
mcpServers: { linear: patch.mcpServers!.linear! },
220+
};
221+
}),
222+
}),
223+
),
224+
),
225+
),
226+
);
227+
});
228+
229+
it.effect("t3_mcp_server_update refuses to keep a secret across a change of transport", () =>
230+
Effect.gen(function* () {
231+
const toolkit = yield* EnvironmentToolkit;
232+
const result = yield* toolkit
233+
.handle("t3_mcp_server_update", {
234+
name: "linear",
235+
server: { command: "linear-mcp", env: { Authorization: { stored: true } } },
236+
})
237+
.pipe(Stream.unwrap, Stream.runCollect);
238+
expect(result.at(-1)?.result).toMatchObject({ code: "invalid_request" });
239+
}).pipe(
240+
Effect.provide(
241+
McpToolAccess.HandlersLayer.layer(EnvironmentHandlers.layer).pipe(
242+
Layer.provideMerge(
243+
layerEnvironment({
244+
getThreadShell: () => Effect.succeed(liveThreadShell(threadId)),
245+
settings: {
246+
...DEFAULT_SERVER_SETTINGS,
247+
mcpServers: {
248+
linear: {
249+
enabled: true,
250+
transport: {
251+
type: "http",
252+
url: "https://mcp.linear.app/mcp",
253+
headers: [
254+
{ name: "Authorization", value: "Bearer lin-secret", sensitive: true },
255+
],
256+
},
257+
},
258+
},
259+
},
260+
updateSettings: () => Effect.die("must not save"),
261+
}),
262+
),
263+
),
264+
),
265+
),
266+
);

‎apps/server/src/mcp/toolkits/environment/handlers.ts‎

Lines changed: 151 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,17 @@
1-
import { OrchestratorMcpFailure, type ServerSettings } from "@t3tools/contracts";
1+
import {
2+
type McpServerConfig,
3+
type McpServerName,
4+
type McpServerVariable,
5+
OrchestratorMcpFailure,
6+
type ProjectId,
7+
type SecretRef,
8+
type ServerSettings,
9+
} from "@t3tools/contracts";
210
import * as Effect from "effect/Effect";
311
import * as Environment from "../../../environment/ServerEnvironment.ts";
412
import * as HostResources from "../../../resourceTelemetry/HostResources.ts";
513
import * as ThreadCommandExecutor from "../../../orchestration-v2/ThreadCommandExecutor.ts";
14+
import * as SecretRequests from "../../../secrets/SecretRequests.ts";
615
import * as Settings from "../../../serverSettings.ts";
716
import * as McpInvocationContext from "../../McpInvocationContext.ts";
817
import * as McpToolAccess from "../../McpToolAccess.ts";
@@ -30,6 +39,117 @@ export function preferences(settings: ServerSettings) {
3039
},
3140
};
3241
}
42+
/** The environment's MCP servers as `t3_mcp_servers_read` shows them: a secret only as `{ stored }`. */
43+
function mcpServersView(settings: ServerSettings) {
44+
const values = (variables: ReadonlyArray<McpServerVariable>) =>
45+
Object.fromEntries(
46+
variables.map((variable) => [
47+
variable.name,
48+
variable.sensitive ? { stored: variable.value !== "" } : variable.value,
49+
]),
50+
);
51+
return {
52+
servers: Object.fromEntries(
53+
Object.entries(settings.mcpServers).map(([name, { enabled, transport }]) => [
54+
name,
55+
transport.type === "stdio"
56+
? {
57+
enabled,
58+
command: transport.command,
59+
args: transport.args,
60+
env: values(transport.env),
61+
}
62+
: { enabled, url: transport.url, headers: values(transport.headers) },
63+
]),
64+
),
65+
};
66+
}
67+
68+
type McpValue =
69+
| string
70+
| { readonly secretRef: SecretRef; readonly prefix?: string }
71+
| { readonly stored: true };
72+
interface McpServerInput {
73+
readonly enabled?: boolean;
74+
readonly command?: string;
75+
readonly args?: ReadonlyArray<string>;
76+
readonly env?: { readonly [name: string]: McpValue };
77+
readonly url?: string;
78+
readonly headers?: { readonly [name: string]: McpValue };
79+
}
80+
const invalid = (message: string) =>
81+
new OrchestratorMcpFailure({ code: "invalid_request", message });
82+
83+
const mcpServerConfig = Effect.fn("EnvironmentToolkit.mcpServerConfig")(function* (
84+
server: McpServerInput,
85+
existing: McpServerConfig | undefined,
86+
projectId: ProjectId | undefined,
87+
) {
88+
if ((server.command === undefined) === (server.url === undefined)) {
89+
return yield* invalid("Give either `command` or `url`.");
90+
}
91+
if (server.command !== undefined && server.headers !== undefined) {
92+
return yield* invalid("`headers` go with `url`.");
93+
}
94+
if (server.url !== undefined && (server.args !== undefined || server.env !== undefined)) {
95+
return yield* invalid("`args` and `env` go with `command`.");
96+
}
97+
const entries = Object.entries(
98+
(server.command === undefined ? server.headers : server.env) ?? {},
99+
);
100+
// Keys are stored per transport (env or header), so one survives only on the same transport.
101+
const sameTransport =
102+
existing !== undefined &&
103+
(server.command !== undefined) === (existing.transport.type === "stdio");
104+
const stored = new Set(
105+
(!sameTransport
106+
? []
107+
: existing.transport.type === "stdio"
108+
? existing.transport.env
109+
: existing.transport.headers
110+
).flatMap((variable) => (variable.sensitive && variable.value !== "" ? [variable.name] : [])),
111+
);
112+
// Checked before any secretRef is used: each one is good for a single save.
113+
for (const [name, value] of entries) {
114+
if (typeof value === "string") continue;
115+
if ("stored" in value && !stored.has(name)) {
116+
return yield* invalid(`No secret is stored for ${name}.`);
117+
}
118+
if ("secretRef" in value && projectId === undefined) {
119+
return yield* invalid("A `secretRef` can only be used from the thread that asked for it.");
120+
}
121+
}
122+
const secretRequests = yield* SecretRequests.SecretRequests;
123+
const variables = yield* Effect.forEach(
124+
entries,
125+
([name, value]): Effect.Effect<McpServerVariable, OrchestratorMcpFailure> =>
126+
typeof value === "string"
127+
? Effect.succeed({ name, value, sensitive: false })
128+
: "stored" in value
129+
? Effect.succeed({ name, value: "", sensitive: true, valueRedacted: true })
130+
: secretRequests.consume({ ref: value.secretRef, projectId: projectId! }).pipe(
131+
Effect.mapError((error) => invalid(error.message)),
132+
Effect.map((secret) => ({
133+
name,
134+
value: (value.prefix ?? "") + secret,
135+
sensitive: true,
136+
})),
137+
),
138+
);
139+
return {
140+
enabled: server.enabled ?? true,
141+
transport:
142+
server.command === undefined
143+
? { type: "http" as const, url: server.url!, headers: variables }
144+
: {
145+
type: "stdio" as const,
146+
command: server.command,
147+
args: server.args ?? [],
148+
env: variables,
149+
},
150+
} satisfies McpServerConfig;
151+
});
152+
33153
const GB = 1e9;
34154
const gigabytes = (bytes: number) => Math.round((bytes / GB) * 10) / 10;
35155

@@ -100,4 +220,34 @@ export const layer = McpToolAccess.toLayer(EnvironmentToolkit, {
100220
: executor.withLock(scope.thread.threadId, update);
101221
}),
102222
),
223+
t3_mcp_servers_read: McpToolAccess.reads(() =>
224+
Effect.gen(function* () {
225+
const { settings } = yield* access;
226+
return mcpServersView(yield* settings.getSettings.pipe(Effect.mapError(unavailable)));
227+
}),
228+
),
229+
t3_mcp_server_update: McpToolAccess.writesEnvironment(({ name, server }, check) =>
230+
Effect.gen(function* () {
231+
const scope = yield* McpInvocationContext.McpInvocationContext;
232+
const executor = yield* ThreadCommandExecutor.ThreadCommandExecutor;
233+
const update = Effect.gen(function* () {
234+
const { caller } = yield* check;
235+
const { settings } = yield* access;
236+
const current = yield* settings.getSettings.pipe(Effect.mapError(unavailable));
237+
const config =
238+
server === null
239+
? null
240+
: yield* mcpServerConfig(server, current.mcpServers[name], caller?.projectId);
241+
const patch: { readonly [key in McpServerName]: McpServerConfig | null } = {
242+
[name]: config,
243+
};
244+
return mcpServersView(
245+
yield* settings.updateSettings({ mcpServers: patch }).pipe(Effect.mapError(unavailable)),
246+
);
247+
});
248+
return yield* scope.thread === undefined
249+
? update
250+
: executor.withLock(scope.thread.threadId, update);
251+
}),
252+
),
103253
});

0 commit comments

Comments
 (0)