Skip to content

armgit / E2B

Public Imported from GitHub
0

Open-source, secure environment with real-world tools for enterprise-grade agents.

Add auth to MCP (#950)

Jonas Scholz5943485644c6
diff --git a/.changeset/pretty-planets-sneeze.md b/.changeset/pretty-planets-sneeze.md
new file mode 100644
index 000000000..186a59dc4
--- /dev/null
+++ b/.changeset/pretty-planets-sneeze.md
@@ -0,0 +1,6 @@
+---
+'@e2b/python-sdk': patch
+'e2b': patch
+---
+
+Add mcp auth
diff --git a/packages/js-sdk/src/sandbox/index.ts b/packages/js-sdk/src/sandbox/index.ts
index adbf93959..c847f0f90 100644
--- a/packages/js-sdk/src/sandbox/index.ts
+++ b/packages/js-sdk/src/sandbox/index.ts
@@ -9,7 +9,6 @@ import {
} from '../connectionConfig'
import { EnvdApiClient, handleEnvdApiError } from '../envd/api'
import { createRpcLogger } from '../logs'
-import { wait } from '../utils'
import { Commands, Pty } from './commands'
import { Filesystem } from './filesystem'
import {
@@ -65,7 +64,7 @@ export interface SandboxUrlOpts {
*/
export class Sandbox extends SandboxApi {
protected static readonly defaultTemplate: string = 'base'
- protected static readonly defaultMcpTemplate: string = 'mcp-gateway-v0'
+ protected static readonly defaultMcpTemplate: string = 'mcp-gateway-v0-1'
protected static readonly defaultSandboxTimeoutMs = DEFAULT_SANDBOX_TIMEOUT_MS
/**
@@ -98,6 +97,7 @@ export class Sandbox extends SandboxApi {
protected readonly envdAccessToken?: string
private readonly envdApiUrl: string
private readonly envdApi: EnvdApiClient
+ private mcpToken?: string
/**
* Use {@link Sandbox.create} to create a new Sandbox instead.
@@ -333,42 +333,20 @@ export class Sandbox extends SandboxApi {
const sandbox = new this({ ...sandboxInfo, ...config }) as InstanceType<S>
if (sandboxOpts?.mcp) {
- const mcpConfigUrl = `${
- config.debug ? 'http' : 'https'
- }://${sandbox.getHost(sandbox.mcpPort)}/config`
-
- const signal = config.getSignal()
-
- let mcpConfigured = false
-
- // TODO: The MCP config seems to succeed on first attempt, but we are keeping the retry logic here for now.
- for (let i = 0; i < 5; i++) {
- try {
- const res = await fetch(mcpConfigUrl, {
- method: 'POST',
- body: JSON.stringify(sandboxOpts?.mcp),
- signal,
- })
-
- if (res.ok) {
- mcpConfigured = true
-
- break
- }
- } catch (e) {
- config.logger?.warn?.(`Failed to configure MCP server: ${e}`)
+ sandbox.mcpToken = crypto.randomUUID()
+
+ const handle = await sandbox.commands.run(
+ `mcp-gateway --config '${JSON.stringify(sandboxOpts?.mcp)}'`,
+ {
+ user: 'root',
+ envs: {
+ GATEWAY_ACCESS_TOKEN: sandbox.mcpToken ?? '',
+ },
+ background: true,
+ timeoutMs: 0,
}
-
- await wait(250)
- }
-
- if (!mcpConfigured) {
- await sandbox.kill()
-
- throw new SandboxError(
- `Failed to configure MCP server. The sandbox template '${template}' might not be configured with MCP gateway inside.`
- )
- }
+ )
+ await handle.disconnect()
}
return sandbox
@@ -582,6 +560,23 @@ export class Sandbox extends SandboxApi {
return `https://${this.getHost(this.mcpPort)}/mcp`
}
+ /**
+ * @beta This feature is in beta and may change in the future.
+ *
+ * Get the MCP token for the sandbox.
+ *
+ * @returns MCP token for the sandbox, or undefined if MCP is not enabled.
+ */
+ async betaGetMcpToken(): Promise<string | undefined> {
+ if (!this.mcpToken) {
+ this.mcpToken = await this.files.read('/etc/mcp-gateway/.token', {
+ user: 'root',
+ })
+ }
+
+ return this.mcpToken
+ }
+
/**
* Get the URL to upload a file to the sandbox.
*
diff --git a/packages/python-sdk/e2b/sandbox/main.py b/packages/python-sdk/e2b/sandbox/main.py
index 893a98464..124e64906 100644
--- a/packages/python-sdk/e2b/sandbox/main.py
+++ b/packages/python-sdk/e2b/sandbox/main.py
@@ -30,7 +30,7 @@ class SandboxBase:
default_sandbox_timeout = 300
default_template = "base"
- default_mcp_template = "mcp-gateway-v0"
+ default_mcp_template = "mcp-gateway-v0-1"
def __init__(
self,
@@ -46,12 +46,21 @@ class SandboxBase:
self.__envd_version = envd_version
self.__envd_access_token = envd_access_token
self.__envd_api_url = f"{'http' if self.connection_config.debug else 'https'}://{self.get_host(self.envd_port)}"
+ self.__mcp_token: Optional[str] = None
@property
def _envd_access_token(self) -> Optional[str]:
"""Private property to access the envd token"""
return self.__envd_access_token
+ @property
+ def _mcp_token(self) -> Optional[str]:
+ return self.__mcp_token
+
+ @_mcp_token.setter
+ def _mcp_token(self, token: str) -> None:
+ self.__mcp_token = token
+
@property
def connection_config(self) -> ConnectionConfig:
return self.__connection_config
diff --git a/packages/python-sdk/e2b/sandbox_async/main.py b/packages/python-sdk/e2b/sandbox_async/main.py
index d4d831215..2a6c8e6eb 100644
--- a/packages/python-sdk/e2b/sandbox_async/main.py
+++ b/packages/python-sdk/e2b/sandbox_async/main.py
@@ -1,7 +1,8 @@
-import asyncio
import datetime
import logging
import httpx
+import uuid
+import json
from typing import Dict, Optional, overload, List
@@ -545,43 +546,17 @@ class AsyncSandbox(SandboxApi):
)
if mcp is not None:
- mcp_url = f"{'http' if sandbox.connection_config.debug else 'https'}://{sandbox.get_host(sandbox.mcp_port)}"
-
- mcp_api = httpx.AsyncClient(
- base_url=mcp_url,
- transport=sandbox._transport,
- headers=sandbox.connection_config.sandbox_headers,
+ token = str(uuid.uuid4())
+ sandbox._mcp_token = token
+
+ handle = await sandbox.commands.run(
+ f"mcp-gateway --config '{json.dumps(mcp)}'",
+ user="root",
+ envs={"GATEWAY_ACCESS_TOKEN": token},
+ background=True,
+ timeout=0,
)
-
- mcp_configured = False
-
- # TODO: The MCP config seems to succeed on first attempt, but we are keeping the retry logic here for now.
- for _ in range(5):
- try:
- res = await mcp_api.post(
- "/config",
- json=mcp,
- timeout=sandbox.connection_config.get_request_timeout(),
- )
-
- if res.status_code == 200:
- mcp_configured = True
-
- break
-
- except Exception as e:
- logger.warning(f"Failed to POST MCP config: {e}")
-
- pass
-
- await asyncio.sleep(0.25)
-
- if not mcp_configured:
- await sandbox.kill()
-
- raise SandboxException(
- f"Failed to configure MCP server. The sandbox template '{template}' might not be configured with MCP gateway inside."
- )
+ await handle.disconnect()
return sandbox
@@ -634,6 +609,20 @@ class AsyncSandbox(SandboxApi):
**opts,
)
+ async def beta_get_mcp_token(self) -> Optional[str]:
+ """
+ [BETA] This feature is in beta and may change in the future.
+
+ Get the MCP token for the sandbox.
+
+ :return: MCP token for the sandbox, or None if MCP is not enabled.
+ """
+ if not self._mcp_token:
+ self._mcp_token = await self.files.read(
+ "/etc/mcp-gateway/.token", user="root"
+ )
+ return self._mcp_token
+
@classmethod
async def _cls_connect(
cls,
diff --git a/packages/python-sdk/e2b/sandbox_sync/main.py b/packages/python-sdk/e2b/sandbox_sync/main.py
index db97cc499..b31e9e907 100644
--- a/packages/python-sdk/e2b/sandbox_sync/main.py
+++ b/packages/python-sdk/e2b/sandbox_sync/main.py
@@ -1,6 +1,7 @@
import datetime
-import time
import logging
+import uuid
+import json
import httpx
@@ -551,41 +552,17 @@ class Sandbox(SandboxApi):
)
if mcp is not None:
- mcp_url = f"{'http' if sandbox.connection_config.debug else 'https'}://{sandbox.get_host(sandbox.mcp_port)}"
-
- mcp_api = httpx.Client(
- base_url=mcp_url,
- transport=sandbox._transport,
- headers=sandbox.connection_config.sandbox_headers,
+ token = str(uuid.uuid4())
+ sandbox._mcp_token = token
+
+ handle = sandbox.commands.run(
+ f"mcp-gateway --config '{json.dumps(mcp)}'",
+ background=True,
+ user="root",
+ envs={"GATEWAY_ACCESS_TOKEN": token},
+ timeout=0,
)
-
- mcp_configured = False
-
- # TODO: The MCP config seems to succeed on first attempt, but we are keeping the retry logic here for now.
- for _ in range(5):
- try:
- res = mcp_api.post(
- "/config",
- json=mcp,
- timeout=sandbox.connection_config.get_request_timeout(),
- )
-
- if res.status_code == 200:
- mcp_configured = True
-
- break
-
- except Exception as e:
- logger.warning(f"Failed to POST MCP config: {e}")
-
- time.sleep(0.25)
-
- if not mcp_configured:
- sandbox.kill()
-
- raise SandboxException(
- f"Failed to configure MCP server. The sandbox template '{template}' might not be configured with MCP gateway inside."
- )
+ handle.disconnect()
return sandbox
@@ -635,6 +612,18 @@ class Sandbox(SandboxApi):
**opts,
)
+ def beta_get_mcp_token(self) -> Optional[str]:
+ """
+ [BETA] This feature is in beta and may change in the future.
+
+ Get the MCP token for the sandbox.
+
+ :return: MCP token for the sandbox, or None if MCP is not enabled.
+ """
+ if not self._mcp_token:
+ self._mcp_token = self.files.read("/etc/mcp-gateway/.token", user="root")
+ return self._mcp_token
+
@classmethod
def _cls_connect(
cls,