smolagents MCPClient: load tools from several servers and clean up by lifecycle
Load tools from a stdio and an HTTP MCP server into one CodeAgent, then close connections with a context manager or try/finally.
Prepare the input and environment · Mechanism and data flow · Workflow map
At a glance
This article relies only on the Tools page of the Hugging Face smolagents documentation. It explains how MCPClient hands tools from several MCP servers to one CodeAgent and how to close the connections afterward. The code is the official excerpt and was not run in this batch; the completion checks and stop rules are editorial recommendations, not official behavior.
Runtime and applicability
- Article type
- Engineering practice
- Verified
- Applies to
- smolagents Documented smolagents task and conditions
Execution locations and responsibilities
- Python application definition and caller Define the configuration or request shown here and check its inputs, outputs and failure branches.
When to use
- A Python environment with smolagents and the mcp package already installed. The excerpts import MCPClient and CodeAgent from smolagents and StdioServerParameters from mcp; this part of the page gives no install command, so verify installation yourself.
When not to use
- The source gives stdio and HTTP forms, the
withand try/finally lifecycles and a security warning. It does not provide a cancellation API, duplicate-name rules, an alias allowlist or an isolation guarantee.
Prepare the input and environment
- A Python environment with smolagents and the mcp package already installed. The excerpts import MCPClient and CodeAgent from smolagents and StdioServerParameters from mcp; this part of the page gives no install command, so verify installation yourself.
- A
modelobject defined outside the excerpts. Both excerpts writemodel=modelwithout defining it; other places on the page build a model with InferenceClientModel, but which model to use and how to supply its credentials is your decision. - For the stdio server,
uvxmust be executable on the machine and you must have explicitly approved running the third-party packagepubmedmcp@0.1.3. The source states that stdio MCP servers always execute code on your machine. - For the HTTP server, a service you control or trust must already be running at
http://127.0.0.1:8000/sse; the example code does not start it. - Decide beforehand which environment variables may reach the child process. The example
envmergesUV_PYTHONwith all ofos.environand passes it to the stdio server. The mapping sets UV_PYTHON to 3.12 first, then expandsos.environ. An existing host variable with that name overrides the default, so the excerpt does not guarantee the final value is 3.12.
Mechanism and data flow
Two kinds of server parameters:A stdio server is described with StdioServerParameters from mcp: command is uvx, args holds --quiet and pubmedmcp@0.1.3, and The environment first defaults UV_PYTHON to 3.12, then expands os.environ; an existing host value overrides that default. A remote server is a plain dict, and the multi-server excerpt points url at http://127.0.0.1:8000/sse. The separate Streamable HTTP excerpt on the page adds a transport key with the value streamable-http and uses the path /mcp. The page does not explain the transport behavior of the /sse dict, so treat it as a documented snippet only and check current documentation before reusing it. In the environment mapping, os.environ is expanded after the UV_PYTHON default, so a matching host key takes precedence. Check the actual host environment before reuse.
Two lifecycle forms:MCPClient accepts either one parameter object or a list. Inside a with statement it yields tools directly, which is how the multi-server excerpt works. For manual control, the other excerpt creates MCPClient(server_parameters), calls get_tools(), runs the agent, and calls mcp_client.disconnect() in finally; its comment says to always ensure the connection is properly closed. The source text does not describe what the end of a with block does beyond showing the pattern, so verify that exit behavior in your own environment.
From the tool collection to one agent:Both excerpts pass the tools to CodeAgent(tools=tools, model=model, add_base_tools=True). Tools from every listed server land in the one tools value, so a single agent can call both servers. The excerpts also pass add_base_tools=True; the page's toolbox section describes tools=[] with that flag as the default toolbox, so the agent may hold tools beyond those from the servers. The page warns that too many tools can overwhelm weaker LLM engines, but it does not say how duplicate tool names across servers are handled.
Trust boundary:The source's security warning says to verify the source and integrity of an MCP server before connecting, especially in production. Only servers from trusted sources should be used, because a malicious server can execute harmful code on your machine. Stdio servers always execute code on your machine, which is their intended function. Remote Streamable HTTP servers will not execute code on your machine, but you should still be careful. The approval for the stdio example therefore has to come before any run.
Official facts versus editorial controls:The layers above report what the page says. The page gives no cancellation API, no result-validation rule and no credential-cleanup procedure. The completion checks, stop conditions and credential cleanup below are editorial recommendations, not official behavior, and none of them has been run.
Workflow map
| Stage | What happens |
|---|---|
| Two kinds of server parameters | A stdio server is described with StdioServerParameters from mcp: command is uvx, args holds --quiet and pubmedmcp@0.1.3, and env sets UV_PYTHON to 3.12 plus everything in os.environ. A host UV_PYTHON overrides the default 3.12. |
| Two lifecycle forms | MCPClient accepts either one parameter object or a list. |
| From the tool collection to one agent | Both excerpts pass the tools to CodeAgent(tools=tools, model=model, add_base_tools=True). |
| Trust boundary | The source's security warning says to verify the source and integrity of an MCP server before connecting, especially in production. |
| Official facts versus editorial controls | The layers above report what the page says. |
Complete the task
Decide on trust and gather inputs:Confirm each prerequisite before writing code: smolagents and mcp are present, model is created outside the excerpt, uvx works, pubmedmcp@0.1.3 is approved, and the service at http://127.0.0.1:8000/sse is running and trusted. Then decide which variables in os.environ the child process may see. If any item is unresolved, do not move on, and do not record the preparation as done.
Write both server parameters:Following the multi-server excerpt, server_params1 is a StdioServerParameters with command, args and env, and server_params2 is a dict containing only url. The excerpt imports os because env uses os.environ. These variable names are only the excerpt's labels and you may rename them, but the contents must match the services you approved.
Pick a lifecycle form:To connect both servers, pass [server_params1, server_params2] to MCPClient inside a with block. If you want to hold the client yourself or print and inspect the result, use the try/finally form: create the client and call get_tools() inside try, and call disconnect() in finally. The page shows get_tools() only with a single parameter object, so do not assume it works with a list. For a manual adaptation, initialize mcp_client=None before try and call disconnect() in finally only after obtaining a client object. If construction created resources without returning a usable client, record cleanup as unconfirmed and investigate in the actual environment; do not claim every connection was closed.
Build the CodeAgent with the tools and model:Pass the resulting tools to CodeAgent(tools=tools, model=model, add_base_tools=True). After construction you can inspect agent.tools, which the page describes as a standard dictionary, to confirm the tool names from both servers are present and to see what extra entries the base tools add. This inspection is an editorial recommendation. If a name is overwritten or an expected tool is missing, stop, because the source gives no duplicate-name rule.
Run the task and keep the result:Call agent.run(...) with the task. The try/finally excerpt stores the return value in result and prints it; the multi-server excerpt does not keep the return value, so assign it to a variable if you need the output. The example question asks for an analysis of recent research and remedies for headaches. That is the official example's prompt, not your task, and nobody has fact-checked its output.
Classify the outcome on four exits:These judgments are editorial recommendations. Success means no exception, the required tools are present, the return value is non-empty and you have reviewed the content against your own criteria. Failure means connecting, get_tools() or run raised an exception, or a required tool is missing; discard any return value. Empty output means tools is empty or the result is empty, and counts as incomplete, not success. User stop means you interrupt from your own runner; the page has no cancel API, so do not assume one.
Clean up and record uncertainty: these controls are editorial recommendations. On normal control-flow exit, call disconnect() only on a client object successfully obtained; check the with form’s exit effects in the actual environment. Finally and context exit require control flow to reach them, so forced termination does not guarantee cleanup. Without a usable client or confirmed exit effects, record resources as pending verification. This page supplies no cancellation API; confirm partial-construction and forced-stop resource states for the actual runtime. Stop only services started for this task and owned by its caller, and remove only temporary credentials added for this task that are no longer needed. This check does not own shutdown of a trusted service that was already running.
Worked example
The official multi-server excerpt combines the pieces like this: server_params1 starts pubmedmcp@0.1.3 through uvx, server_params2 points to http://127.0.0.1:8000/sse, both go to MCPClient as a list, and the resulting tools go to CodeAgent with the task of analyzing recent research and suggesting remedies for headaches. The reader must prepare model, approve the stdio package and have the local HTTP service running first. The official example shows no output and this batch did not run it, so there is no observed result here; after your own run, judge it with step six and clean up with step seven.
from smolagents import MCPClient, CodeAgent
from mcp import StdioServerParameters
import os
# Initialize server parameters
server_parameters = StdioServerParameters(
command="uvx",
args=["--quiet", "pubmedmcp@0.1.3"],
env={"UV_PYTHON": "3.12", **os.environ},
)
# Manually manage the connection
try:
mcp_client = MCPClient(server_parameters)
tools = mcp_client.get_tools()
# Use the tools with your agent
agent = CodeAgent(tools=tools, model=model, add_base_tools=True)
result = agent.run("What are the recent therapeutic approaches for Alzheimer's disease?")
# Process the result as needed
print(f"Agent response: {result}")
finally:
# Always ensure the connection is properly closed
mcp_client.disconnect()from smolagents import MCPClient, CodeAgent
from mcp import StdioServerParameters
import os
server_params1 = StdioServerParameters(
command="uvx",
args=["--quiet", "pubmedmcp@0.1.3"],
env={"UV_PYTHON": "3.12", **os.environ},
)
server_params2 = {"url": "http://127.0.0.1:8000/sse"}
with MCPClient([server_params1, server_params2]) as tools:
agent = CodeAgent(tools=tools, model=model, add_base_tools=True)
agent.run("Please analyze the latest research and suggest remedies for headaches.")Check the result and failure paths
- Static check: confirm the excerpt text is unchanged,
modelis defined in your code, and both server parameters match what you approved. This can only find omissions and does not prove semantic correctness. - After-run check: no exception, the expected server tools appear in
agent.tools, the return value is non-empty, and you have reviewed its content. These are the editorial completion criteria. - Failure and empty-output check: an exception at any stage, a missing tool, an empty
toolsor an empty result is recorded as incomplete and never written up as success. - Cleanup check (editorial): verify closure of the client actually obtained. Stop only caller-owned services started for this task, and clear only temporary credentials added for this task. Construction without a returned client, forced termination or unchecked context exit leaves cleanup unconfirmed rather than complete.
Scope and limits
- This page is not a tutorial on custom Tool classes, Managed Agents or executor isolation; a stdio server executes code on your machine, and the forms shown here do not isolate it.
- The
/ssedict is explained only as this documentation snippet, so no other transport requirements can be inferred from it; options such asstructured_outputare outside this flow.
No product, API, server or example code was run in this batch, and no dependencies were installed; everything here comes from reading the s1 page. Example results, success states and cleanup effects were not observed, and the completion checks and manual control steps are editorial recommendations, not official behavior.
Sources
All links are official pages; verification dates are listed per source, and links point to the version checked.