Skip to content

armgit / E2B

Public Imported from GitHub
0

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

Promote beta MCP features to main (#986)

Mish Ushakovc43280516178
diff --git a/.changeset/nasty-lamps-listen.md b/.changeset/nasty-lamps-listen.md
new file mode 100644
index 000000000..d49bdc57e
--- /dev/null
+++ b/.changeset/nasty-lamps-listen.md
@@ -0,0 +1,6 @@
+---
+'@e2b/python-sdk': minor
+'e2b': minor
+---
+
+added mcp functionality
diff --git a/packages/js-sdk/src/sandbox/index.ts b/packages/js-sdk/src/sandbox/index.ts
index d73fdf344..3ba18bc2f 100644
--- a/packages/js-sdk/src/sandbox/index.ts
+++ b/packages/js-sdk/src/sandbox/index.ts
@@ -237,8 +237,16 @@ export class Sandbox extends SandboxApi {
): Promise<InstanceType<S>> {
const { template, sandboxOpts } =
typeof templateOrOpts === 'string'
- ? { template: templateOrOpts, sandboxOpts: opts }
- : { template: this.defaultTemplate, sandboxOpts: templateOrOpts }
+ ? {
+ template: templateOrOpts,
+ sandboxOpts: opts,
+ }
+ : {
+ template: templateOrOpts?.mcp
+ ? this.defaultMcpTemplate
+ : this.defaultTemplate,
+ sandboxOpts: templateOrOpts,
+ }
const config = new ConnectionConfig(sandboxOpts)
if (config.debug) {
@@ -249,13 +257,31 @@ export class Sandbox extends SandboxApi {
}) as InstanceType<S>
}
- const sandbox = await SandboxApi.createSandbox(
+ const sandboxInfo = await SandboxApi.createSandbox(
template,
sandboxOpts?.timeoutMs ?? this.defaultSandboxTimeoutMs,
sandboxOpts
)
- return new this({ ...sandbox, ...config }) as InstanceType<S>
+ const sandbox = new this({ ...sandboxInfo, ...config }) as InstanceType<S>
+
+ if (sandboxOpts?.mcp) {
+ sandbox.mcpToken = crypto.randomUUID()
+ const res = await sandbox.commands.run(
+ `mcp-gateway --config '${JSON.stringify(sandboxOpts?.mcp)}'`,
+ {
+ user: 'root',
+ envs: {
+ GATEWAY_ACCESS_TOKEN: sandbox.mcpToken ?? '',
+ },
+ }
+ )
+ if (res.exitCode !== 0) {
+ throw new Error(`Failed to start MCP gateway: ${res.stderr}`)
+ }
+ }
+
+ return sandbox
}
/**
@@ -551,24 +577,21 @@ export class Sandbox extends SandboxApi {
}
/**
- * @beta This feature is in beta and may change in the future.
*
* Get the MCP URL for the sandbox.
*
* @returns MCP URL for the sandbox.
*/
- betaGetMcpUrl(): string {
+ getMcpUrl(): string {
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> {
+ async getMcpToken(): Promise<string | undefined> {
if (!this.mcpToken) {
this.mcpToken = await this.files.read('/etc/mcp-gateway/.token', {
user: 'root',
diff --git a/packages/js-sdk/src/sandbox/sandboxApi.ts b/packages/js-sdk/src/sandbox/sandboxApi.ts
index 7a1feda25..a7ebed21b 100644
--- a/packages/js-sdk/src/sandbox/sandboxApi.ts
+++ b/packages/js-sdk/src/sandbox/sandboxApi.ts
@@ -84,6 +84,12 @@ export interface SandboxOpts extends ConnectionOpts {
* @default true
*/
allowInternetAccess?: boolean
+
+ /**
+ * MCP server to enable in the sandbox
+ * @default undefined
+ */
+ mcp?: McpServer
}
export type SandboxBetaCreateOpts = SandboxOpts & {
@@ -92,12 +98,6 @@ export type SandboxBetaCreateOpts = SandboxOpts & {
* @default false
*/
autoPause?: boolean
-
- /**
- * MCP server to enable in the sandbox
- * @default undefined
- */
- mcp?: McpServer
}
/**
diff --git a/packages/js-sdk/src/template/index.ts b/packages/js-sdk/src/template/index.ts
index 2c872e70a..8fa0cb3c7 100644
--- a/packages/js-sdk/src/template/index.ts
+++ b/packages/js-sdk/src/template/index.ts
@@ -488,7 +488,7 @@ export class TemplateBase
)
}
- betaAddMcpServer(servers: McpServerName | McpServerName[]): TemplateBuilder {
+ addMcpServer(servers: McpServerName | McpServerName[]): TemplateBuilder {
if (this.baseTemplate !== 'mcp-gateway') {
throw new BuildError(
'MCP servers can only be added to mcp-gateway template',
diff --git a/packages/js-sdk/src/template/types.ts b/packages/js-sdk/src/template/types.ts
index db848549f..a6a808523 100644
--- a/packages/js-sdk/src/template/types.ts
+++ b/packages/js-sdk/src/template/types.ts
@@ -487,11 +487,11 @@ export interface TemplateBuilder {
* @throws {Error} If the base template is not mcp-gateway
* @example
* ```ts
- * template.betaAddMcpServer('exa')
- * template.betaAddMcpServer(['brave', 'firecrawl', 'duckduckgo'])
+ * template.addMcpServer('exa')
+ * template.addMcpServer(['brave', 'firecrawl', 'duckduckgo'])
* ```
*/
- betaAddMcpServer(servers: McpServerName | McpServerName[]): TemplateBuilder
+ addMcpServer(servers: McpServerName | McpServerName[]): TemplateBuilder
/**
* Clone a Git repository.
diff --git a/packages/js-sdk/tests/template/stacktrace.test.ts b/packages/js-sdk/tests/template/stacktrace.test.ts
index 96630cb0b..81fc33b1e 100644
--- a/packages/js-sdk/tests/template/stacktrace.test.ts
+++ b/packages/js-sdk/tests/template/stacktrace.test.ts
@@ -243,9 +243,9 @@ buildTemplateTest('traces on setStartCmd', async ({ buildTemplate }) => {
}, 'setStartCmd')
})
-buildTemplateTest('traces on betaAddMcpServer', async () => {
+buildTemplateTest('traces on addMcpServer', async () => {
// needs mcp-gateway as base template, without it no mcp servers can be added
await expectToThrowAndCheckTrace(async () => {
- Template().fromBaseImage().betaAddMcpServer('exa')
- }, 'betaAddMcpServer')
+ Template().fromBaseImage().addMcpServer('exa')
+ }, 'addMcpServer')
})
diff --git a/packages/python-sdk/e2b/sandbox/main.py b/packages/python-sdk/e2b/sandbox/main.py
index 6889c9052..b0a5f3b22 100644
--- a/packages/python-sdk/e2b/sandbox/main.py
+++ b/packages/python-sdk/e2b/sandbox/main.py
@@ -200,10 +200,8 @@ class SandboxBase:
return f"{port}-{self.sandbox_id}.{self.sandbox_domain}"
- def beta_get_mcp_url(self) -> str:
+ def get_mcp_url(self) -> str:
"""
- [BETA] This feature is in beta and may change in the future.
-
Get the MCP URL for the sandbox.
:returns MCP URL for the sandbox.
diff --git a/packages/python-sdk/e2b/sandbox_async/main.py b/packages/python-sdk/e2b/sandbox_async/main.py
index 79197da28..c46a725cb 100644
--- a/packages/python-sdk/e2b/sandbox_async/main.py
+++ b/packages/python-sdk/e2b/sandbox_async/main.py
@@ -162,8 +162,9 @@ class AsyncSandbox(SandboxApi):
timeout: Optional[int] = None,
metadata: Optional[Dict[str, str]] = None,
envs: Optional[Dict[str, str]] = None,
- secure: Optional[bool] = True,
+ secure: bool = True,
allow_internet_access: bool = True,
+ mcp: Optional[McpServer] = None,
**opts: Unpack[ApiParams],
) -> Self:
"""
@@ -177,22 +178,43 @@ class AsyncSandbox(SandboxApi):
:param envs: Custom environment variables for the sandbox
:param secure: Envd is secured with access token and cannot be used without it, defaults to `True`.
:param allow_internet_access: Allow sandbox to access the internet, defaults to `True`.
+ :param mcp: MCP server to enable in the sandbox
:return: A Sandbox instance for the new sandbox
Use this method instead of using the constructor to create a new sandbox.
"""
- return await cls._create(
+ if not template and mcp is not None:
+ template = cls.default_mcp_template
+ elif not template:
+ template = cls.default_template
+
+ sandbox = await cls._create(
template=template,
timeout=timeout,
+ auto_pause=False,
metadata=metadata,
envs=envs,
secure=secure,
allow_internet_access=allow_internet_access,
- auto_pause=False,
+ mcp=mcp,
**opts,
)
+ if mcp is not None:
+ token = str(uuid.uuid4())
+ sandbox._mcp_token = token
+
+ res = await sandbox.commands.run(
+ f"mcp-gateway --config '{json.dumps(mcp)}'",
+ user="root",
+ envs={"GATEWAY_ACCESS_TOKEN": token},
+ )
+ if res.exit_code != 0:
+ raise Exception(f"Failed to start MCP gateway: {res.stderr}")
+
+ return sandbox
+
@overload
async def connect(
self,
@@ -609,10 +631,8 @@ class AsyncSandbox(SandboxApi):
**opts,
)
- async def beta_get_mcp_token(self) -> Optional[str]:
+ async def 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.
diff --git a/packages/python-sdk/e2b/sandbox_sync/main.py b/packages/python-sdk/e2b/sandbox_sync/main.py
index cc9dc97fe..7ee2b786f 100644
--- a/packages/python-sdk/e2b/sandbox_sync/main.py
+++ b/packages/python-sdk/e2b/sandbox_sync/main.py
@@ -167,6 +167,7 @@ class Sandbox(SandboxApi):
envs: Optional[Dict[str, str]] = None,
secure: bool = True,
allow_internet_access: bool = True,
+ mcp: Optional[McpServer] = None,
**opts: Unpack[ApiParams],
) -> Self:
"""
@@ -180,22 +181,43 @@ class Sandbox(SandboxApi):
:param envs: Custom environment variables for the sandbox
:param secure: Envd is secured with access token and cannot be used without it, defaults to `True`.
:param allow_internet_access: Allow sandbox to access the internet, defaults to `True`.
+ :param mcp: MCP server to enable in the sandbox
:return: A Sandbox instance for the new sandbox
Use this method instead of using the constructor to create a new sandbox.
"""
- return cls._create(
+ if not template and mcp is not None:
+ template = cls.default_mcp_template
+ elif not template:
+ template = cls.default_template
+
+ sandbox = cls._create(
template=template,
+ auto_pause=False,
timeout=timeout,
metadata=metadata,
envs=envs,
secure=secure,
allow_internet_access=allow_internet_access,
- auto_pause=False,
+ mcp=mcp,
**opts,
)
+ if mcp is not None:
+ token = str(uuid.uuid4())
+ sandbox._mcp_token = token
+
+ res = sandbox.commands.run(
+ f"mcp-gateway --config '{json.dumps(mcp)}'",
+ user="root",
+ envs={"GATEWAY_ACCESS_TOKEN": token},
+ )
+ if res.exit_code != 0:
+ raise Exception(f"Failed to start MCP gateway: {res.stderr}")
+
+ return sandbox
+
@overload
def connect(
self,
@@ -612,10 +634,8 @@ class Sandbox(SandboxApi):
**opts,
)
- def beta_get_mcp_token(self) -> Optional[str]:
+ def 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.
diff --git a/packages/python-sdk/e2b/template/main.py b/packages/python-sdk/e2b/template/main.py
index 9aa7dd734..c35afce22 100644
--- a/packages/python-sdk/e2b/template/main.py
+++ b/packages/python-sdk/e2b/template/main.py
@@ -425,7 +425,7 @@ class TemplateBuilder:
)
)
- def beta_add_mcp_server(self, servers: Union[str, List[str]]) -> "TemplateBuilder":
+ def add_mcp_server(self, servers: Union[str, List[str]]) -> "TemplateBuilder":
"""
Install MCP servers using mcp-gateway.
@@ -437,8 +437,8 @@ class TemplateBuilder:
Example
```python
- template.beta_add_mcp_server('exa')
- template.beta_add_mcp_server(['brave', 'firecrawl', 'duckduckgo'])
+ template.add_mcp_server('exa')
+ template.add_mcp_server(['brave', 'firecrawl', 'duckduckgo'])
```
"""
if self._template._base_template != "mcp-gateway":
diff --git a/packages/python-sdk/tests/async/template_async/test_stacktrace.py b/packages/python-sdk/tests/async/template_async/test_stacktrace.py
index d1cf52982..eb67d5015 100644
--- a/packages/python-sdk/tests/async/template_async/test_stacktrace.py
+++ b/packages/python-sdk/tests/async/template_async/test_stacktrace.py
@@ -211,9 +211,9 @@ async def test_traces_on_start_cmd(async_build):
@pytest.mark.skip_debug()
-async def test_traces_on_beta_add_mcp_server():
+async def test_traces_on_add_mcp_server():
# needs mcp-gateway as base template, without it no mcp servers can be added
await _expect_to_throw_and_check_trace(
- lambda: AsyncTemplate().from_base_image().beta_add_mcp_server("exa"),
- "beta_add_mcp_server",
+ lambda: AsyncTemplate().from_base_image().add_mcp_server("exa"),
+ "add_mcp_server",
)
diff --git a/packages/python-sdk/tests/sync/template_sync/test_stacktrace.py b/packages/python-sdk/tests/sync/template_sync/test_stacktrace.py
index 8ad4f31d8..dbd393de4 100644
--- a/packages/python-sdk/tests/sync/template_sync/test_stacktrace.py
+++ b/packages/python-sdk/tests/sync/template_sync/test_stacktrace.py
@@ -199,9 +199,9 @@ def test_traces_on_set_start_cmd(build):
@pytest.mark.skip_debug()
-def test_traces_on_beta_add_mcp_server():
+def test_traces_on_add_mcp_server():
# needs mcp-gateway as base template, without it no mcp servers can be added
_expect_to_throw_and_check_trace(
- lambda: Template().from_base_image().beta_add_mcp_server("exa"),
- "beta_add_mcp_server",
+ lambda: Template().from_base_image().add_mcp_server("exa"),
+ "add_mcp_server",
)