Skip to content

Commit 5508697

Browse files
committed
Inherit environment variables deemed safe by default
1 parent 60e9c7a commit 5508697

File tree

1 file changed

+34
-3
lines changed

1 file changed

+34
-3
lines changed

mcp_python/client/stdio.py

Lines changed: 34 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import os
12
import sys
23
from contextlib import asynccontextmanager
34

@@ -10,18 +11,46 @@
1011
from mcp_python.types import JSONRPCMessage
1112

1213

14+
# Environment variables to inherit by default
15+
DEFAULT_INHERITED_ENV_VARS = (
16+
["APPDATA", "HOMEDRIVE", "HOMEPATH", "LOCALAPPDATA", "PATH",
17+
"PROCESSOR_ARCHITECTURE", "SYSTEMDRIVE", "SYSTEMROOT", "TEMP",
18+
"USERNAME", "USERPROFILE"]
19+
if sys.platform == "win32"
20+
else ["HOME", "LOGNAME", "PATH", "SHELL", "TERM", "USER"]
21+
)
22+
23+
24+
def get_default_environment() -> dict[str, str]:
25+
"""Returns a default environment object including only environment variables deemed safe to inherit."""
26+
env: dict[str, str] = {}
27+
28+
for key in DEFAULT_INHERITED_ENV_VARS:
29+
value = os.environ.get(key)
30+
if value is None:
31+
continue
32+
33+
if value.startswith("()"):
34+
# Skip functions, which are a security risk
35+
continue
36+
37+
env[key] = value
38+
39+
return env
40+
41+
1342
class StdioServerParameters(BaseModel):
1443
command: str
1544
"""The executable to run to start the server."""
1645

1746
args: list[str] = Field(default_factory=list)
1847
"""Command line arguments to pass to the executable."""
1948

20-
env: dict[str, str] = Field(default_factory=dict)
49+
env: dict[str, str] | None = None
2150
"""
2251
The environment to use when spawning the process.
2352
24-
The environment is NOT inherited from the parent process by default.
53+
If not specified, the result of get_default_environment() will be used.
2554
"""
2655

2756

@@ -41,7 +70,9 @@ async def stdio_client(server: StdioServerParameters):
4170
write_stream, write_stream_reader = anyio.create_memory_object_stream(0)
4271

4372
process = await anyio.open_process(
44-
[server.command, *server.args], env=server.env, stderr=sys.stderr
73+
[server.command, *server.args],
74+
env=server.env if server.env is not None else get_default_environment(),
75+
stderr=sys.stderr
4576
)
4677

4778
async def stdout_reader():

0 commit comments

Comments
 (0)