Skip to content

Commit d9bf75b

Browse files
committed
Substitue env in header of mcp
1 parent 4d0f850 commit d9bf75b

File tree

1 file changed

+32
-3
lines changed

1 file changed

+32
-3
lines changed

common/src/mcp/client.ts

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,34 @@ const listToolsCache: Record<
1818
ReturnType<typeof Client.prototype.listTools>
1919
> = {}
2020

21+
/**
22+
* Substitutes environment variable references ($VAR_NAME) in a string with their values.
23+
* Supports both simple replacement ("$VAR_NAME") and interpolation ("Bearer $VAR_NAME").
24+
*/
25+
function substituteEnvInValue(value: string): string {
26+
return value.replace(/\$([A-Z_][A-Z0-9_]*)/g, (match, varName) => {
27+
const envValue = process.env[varName]
28+
if (envValue === undefined) {
29+
// Return original if env var not found
30+
return match
31+
}
32+
return envValue
33+
})
34+
}
35+
36+
/**
37+
* Substitutes environment variable references in all values of a record.
38+
*/
39+
function substituteEnvInRecord(
40+
record: Record<string, string>,
41+
): Record<string, string> {
42+
const result: Record<string, string> = {}
43+
for (const [key, value] of Object.entries(record)) {
44+
result[key] = substituteEnvInValue(value)
45+
}
46+
return result
47+
}
48+
2149
function hashConfig(config: MCPConfig): string {
2250
if (config.type === 'stdio') {
2351
return JSON.stringify({
@@ -57,24 +85,25 @@ export async function getMCPClient(config: MCPConfig): Promise<string> {
5785
transport = new StdioClientTransport({
5886
command: config.command,
5987
args: config.args,
60-
env: config.env,
88+
env: substituteEnvInRecord(config.env),
6189
stderr: 'ignore',
6290
})
6391
} else {
6492
const url = new URL(config.url)
6593
for (const [key, value] of Object.entries(config.params)) {
6694
url.searchParams.set(key, value)
6795
}
96+
const headers = substituteEnvInRecord(config.headers)
6897
if (config.type === 'http') {
6998
transport = new StreamableHTTPClientTransport(url, {
7099
requestInit: {
71-
headers: config.headers,
100+
headers,
72101
},
73102
})
74103
} else if (config.type === 'sse') {
75104
transport = new SSEClientTransport(url, {
76105
requestInit: {
77-
headers: config.headers,
106+
headers,
78107
},
79108
})
80109
} else {

0 commit comments

Comments
 (0)