# Smolagents MCP Guide: ToolCollection from MCP for Cloud Storage

Hugging Face smolagents can query enterprise cloud storage without overloading model context by integrating the Model Context Protocol. By using ToolCollection.from_mcp to connect CodeAgents to remote indexed workspaces over Streamable HTTP, Python agents search Dropbox, Box, Google Drive, and OneDrive archives directly through semantic queries rather than heavy local filesystem syncs.

Source: https://fast.io/resources/smolagents-mcp/
Author: [Tom Langridge](https://fast.io/authors/tom-langridge/)
Last reviewed: 2026-10-07

## How Smolagents MCP Loads Remote Tools with ToolCollection.from_mcp

When autonomous Python agents process corporate records, pointing an execution sandbox at unindexed cloud drives causes context exhaustion, file locking collisions, and high token overhead. Hugging Face smolagents addresses agentic tool execution by allowing CodeAgents to generate and run native Python code rather than serializing multi-step JSON tool calls. However, connecting those agents to remote cloud storage requires a protocol that bridges sandboxed Python environments with indexed cloud workspaces without pulling multi-gigabyte directories across the network.

Smolagents MCP is the native integration in Hugging Face smolagents library that dynamically loads tools from Model Context Protocol servers using ToolCollection.from_mcp for execution by CodeAgents and ToolCallingAgents.

ToolCollection.from_mcp loads tools directly into Python CodeAgent execution sandboxes with zero custom wrapper code. Instead of hand-crafting API requests or maintaining custom tool wrappers for every cloud provider, developers point smolagents at a Model Context Protocol (MCP) server. The method inspects the server manifest, discovers exposed tools, translates JSON-RPC schemas into native agent tools, and mounts them inside the execution environment.

```python
import os
from smolagents import CodeAgent, HfApiModel, ToolCollection

server_params = {
    "url": "https://mcp.fast.io/mcp/code",
    "transport": "streamable-http",
    "headers": {
        "Authorization": f"Bearer {os.environ.get('FASTIO_API_KEY')}"
    }
}

with ToolCollection.from_mcp(server_params, trust_remote_code=True) as tool_collection:
    agent = CodeAgent(
        tools=[*tool_collection.tools],
        model=HfApiModel(model_id="Qwen/Qwen2.5-Coder-32B-Instruct"),
        add_base_tools=True,
    )
    agent.run("Search the workspace for recent quarterly financial disclosures.")
```

Most published agent tutorials demonstrate only local mock tools or arithmetic examples, omitting how smolagents query remote cloud storage or enterprise workspaces where live corporate knowledge resides. When an agent needs to answer questions from thousands of corporate PDFs, spreadsheets, and design specs, local mock functions fail.

CodeAgents execute Python code calls to MCP tools, reducing multi-step tool-calling round-trips compared to JSON-based agents. In standard JSON tool-calling architectures, each tool invocation requires a full round-trip between the agent loop and the language model. When an agent needs to search a folder, filter files by date, and inspect three documents, a traditional JSON agent makes multiple successive round-trips. A smolagents CodeAgent generates a single Python code block that calls the search tool, loops through results, filters by date, and retrieves matching document snippets within a single execution step.

```
+-------------------------------------------------------------------------+
|                  Hugging Face smolagents Environment                    |
|             (CodeAgent / Python Sandbox Execution Loop)                 |
+-------------------------------------------------------------------------+
                                    |
                    (ToolCollection.from_mcp Client)
                                    |
                  (Streamable HTTP / JSON-RPC Protocol)
                                    |
                                    v
+-------------------------------------------------------------------------+
|                        Remote Fast.io Workspace                         |
|   (Auto-Indexing / Hybrid Full-Text + Semantic Vector RAG Engine)       |
+-------------------------------------------------------------------------+
          |                         |                         |
(Dropbox Cloud Sync)        (Box Cloud Sync)        (OneDrive Cloud Sync)
```

By connecting smolagents to indexed remote storage through ToolCollection.from_mcp, developers maintain a clean separation of concerns: the agent handles logic in Python code, while the cloud workspace handles search, retrieval, document extraction, and file persistence.

## Why Local Stdio Storage Fails in CodeAgent Sandboxes

Enterprise teams already store critical project documentation, contracts, research data, and media across Dropbox, Google Drive, Microsoft OneDrive, Box, or SharePoint. Developers attempting to connect smolagents to those files typically rely on one of three architectural approaches, each introducing severe operational failures:

1. **Local Stdio Filesystem Servers and Files On-Demand Stubs:** Running the standard filesystem MCP server (`@modelcontextprotocol/server-filesystem`) over standard input and output (stdio) pointed at local synchronization folders like `~/Dropbox`, `~/OneDrive`, or `~/Box`. Modern cloud sync applications rely on virtual filesystem stubs rather than storing complete files on local disks. When an agent attempts to open a stub file, the operating system triggers a background download interrupt that stalls the Python execution sandbox, resulting in execution timeouts.
2. **Sync Collision Locks and Corrupted Revisions:** Cloud storage clients run background daemon engines that scan for local disk modifications. When a smolagent writes generated reports, extracted tables, or transformed code into a synchronized folder, the cloud client locks the file to compute checksums and initiate upload transfers. Rapid sequential writes from an agent collide with this sync daemon lock, producing file system permission errors and duplicate conflict files.
3. **Direct Cloud REST Connectors and Context Exhaustion:** Interfacing directly with native cloud APIs like the Google Drive API, Box API, or Microsoft Graph API. These native connectors require maintaining OAuth client credentials, managing refresh tokens, and handling complex pagination. More critically, native connectors return raw file streams or entire document bodies. When an agent requests a file, the connector transfers the entire multi-megabyte payload into the model context window. Ingesting full documents quickly exhausts context budgets, increases token costs, and degrades model reasoning accuracy.

The effective solution is a decoupled cloud workspace architecture. Instead of requiring smolagents to parse raw file blobs or navigate local synchronization folders, teams maintain their existing storage in Dropbox, Box, Google Drive, or OneDrive, and synchronize those directories into an org-owned Fast.io workspace. The workspace indexes the corpus in the cloud using hybrid search. The agent connects to the workspace through a remote MCP server over Streamable HTTP and searches the index, pulling only the relevant text passages and citations.

Comparative evaluations of connector performance are published at [Fast.io benchmarks](https://fast.io/benchmarks/). By querying indexed workspace endpoints rather than traversing unindexed cloud folders, assistants retrieve exact information while minimizing network overhead and context consumption.

## How to Connect Smolagents to Remote Fast.io Cloud Workspaces

Connecting Hugging Face smolagents to remote cloud storage requires configuring `ToolCollection.from_mcp` with an HTTP transport configuration. For coding environments, automated scripts, and agent frameworks, Fast.io exposes an MCP endpoint over Streamable HTTP at `https://mcp.fast.io/mcp/code`.

When connecting from programmatic Python scripts, authenticate by providing your scoped API key in the `Authorization` header. You can review setup steps in the official documentation at [Fast.io MCP setup](https://mcp.fast.io/docs) and inspect tool definitions in [Fast.io MCP specifications](https://mcp.fast.io/skill.md).

Here is a complete, runnable Python implementation demonstrating how to connect a smolagents CodeAgent to a remote Fast.io workspace:

```python
import os
from smolagents import CodeAgent, HfApiModel, ToolCollection

fastio_server_parameters = {
    "url": "https://mcp.fast.io/mcp/code",
    "transport": "streamable-http",
    "headers": {
        "Authorization": f"Bearer {os.environ.get('FASTIO_API_KEY')}"
    },
}

def run_workspace_assistant(query: str):
    with ToolCollection.from_mcp(
        fastio_server_parameters,
        trust_remote_code=True,
        structured_output=True,
    ) as tool_collection:
        print("Loaded tools from Fast.io MCP server:")
        for tool in tool_collection.tools:
            print(f" - {tool.name}: {tool.description}")
        agent = CodeAgent(
            tools=[*tool_collection.tools],
            model=HfApiModel(model_id="Qwen/Qwen2.5-Coder-32B-Instruct"),
            add_base_tools=True,
            max_steps=6,
        )
        response = agent.run(query)
        return response

if __name__ == "__main__":
    task_prompt = (
        "Find the contract renewal terms for vendor Acme Corp in the workspace, "
        "check the effective dates, and summarize the liability clause."
    )
    result = run_workspace_assistant(task_prompt)
    print("Agent Execution Result:", result)
```

### Understanding the Technical Parameters

This configuration addresses several core mechanics of remote MCP integration in smolagents:

- **Streamable HTTP Transport:** Specifying `"transport": "streamable-http"` establishes persistent bidirectional communication over HTTP rather than launching a local subprocess. Requests and tool calls execute as standard JSON-RPC payloads over TLS, allowing agents to run in lightweight serverless containers or cloud sandboxes without local filesystem dependencies.
- **Lifecycle Management with Context Managers:** Using `with ToolCollection.from_mcp(...)` ensures the background asyncio event loop and network sessions initialize and terminate cleanly. The smolagents library spawns a dedicated background thread to manage async MCP communication while exposing synchronous tool execution to the CodeAgent.
- **Security Validation with trust_remote_code:** Setting `trust_remote_code=True` informs smolagents that you acknowledge and trust the tools provided by the remote server. Because MCP tools define input schemas and execution routines, explicit trust confirmation is required.
- **Structured Output Support:** Passing `structured_output=True` enables parsing of structured tool response schemas, ensuring that metadata, status codes, and search rankings returned by the MCP endpoint pass cleanly to the agent.

## How Fast.io Hybrid Search Prevents CodeAgent Context Overflow

Connecting smolagents to cloud storage does not require abandoning established corporate file systems. Fast.io operates alongside existing storage providers, synchronizing folder trees into organized cloud workspaces.

Fast.io provides Cloud Sync for Google Drive, Dropbox, Box, and OneDrive. Sync can be configured as one-way or two-way, operating on a schedule or on demand. Cloud Sync is never continuous, live, or real-time, which eliminates file locking conflicts and synchronization races. For organizations using Microsoft SharePoint, document libraries connect directly through the OneDrive connector.

Once assets sync into a Fast.io workspace, Intelligence Mode indexes the content automatically. Unlike standard keyword search utilities, Intelligence Mode implements hybrid search, combining full-text keyword indexing with semantic vector embeddings.

```
+-------------------------------------------------------------------------+
|                  Fast.io Hybrid Search Architecture                     |
+-------------------------------------------------------------------------+
|                                                                         |
|  Incoming Files (Google Drive / Dropbox / Box / OneDrive / URL Import)  |
|       |                                                                 |
|       v                                                                 |
|   Text Extraction Engine  (PDFs, Markdown, Word, Spreadsheets, Code)    |
|       |                                                                 |
|       +-----------------------------------+                             |
|       |                                   |                             |
|       v                                   v                             |
|   Full-Text Keyword Index         Semantic Vector Embeddings            |
|  (Exact terms, IDs, numbers)     (Conceptual contextual matching)       |
|       |                                   |                             |
|       +-----------------+-----------------+                             |
|                         |                                               |
|                         v                                               |
|            Unified Storage Search API                                   |
|           (Ranked Results with Document Citations)                      |
|                         |                                               |
+-------------------------------------------------------------------------+
                          |
             (Streamable HTTP JSON-RPC)
                          |
                          v
         smolagents CodeAgent Execution Context
```

When a smolagent runs a search query against the workspace, it calls the `search` action over the MCP endpoint. Instead of returning raw multi-page PDF files that flood the LLM context window, hybrid search retrieves the specific matching passages along with document identifiers and page numbers. The CodeAgent receives focused snippets, preserving its context budget for analytical reasoning and code generation.

### Structured Data Extraction with Metadata Views

Beyond unstructured prose and technical documentation, engineering and operations teams routinely handle semi-structured business files like statements of work, vendor invoices, security audits, and purchase receipts.

For these documents, [Fast.io Metadata Views](/product/document-data-extraction/) turn unstructured files into live, queryable databases. Users describe the fields they want extracted in natural language, and AI designs a typed schema (Text, Integer, Decimal, Boolean, URL, JSON, Date & Time), matches relevant files in the workspace, and populates a structured spreadsheet. No manual OCR template configuration or brittle regex maintenance is needed.

Smolagents can query Metadata Views directly over the MCP server. Instead of instructing a CodeAgent to open and inspect every PDF invoice in a folder to calculate quarterly vendor spend, the agent queries the Metadata View, retrieves structured numbers immediately, and executes aggregation logic in Python.

## Steps for Coordinating Multi-Agent File Operations and Versioning

Autonomous agents rarely operate in isolation. In modern engineering workflows, multiple agents and human team members collaborate across shared file sets. A research agent built with smolagents might extract regulatory data, a coding agent in Claude Code might update backend models, and human engineers review documentation in the web interface. Coordinating these file operations requires structured multi-agent primitives.

### File Version History

When autonomous processes update files in cloud storage, overwriting existing records risks permanent data loss. Fast.io maintains complete, per-file version history across all workspace assets. Every programmatic file update submitted through the MCP endpoint generates a new version rather than destroying prior states. If two agent processes write to the same file concurrently, version history preserves each revision, allowing human supervisors to inspect diffs and restore earlier versions.

### Advisory File Locks

For operations requiring sequential execution or multi-file transactions, Fast.io provides advisory file leases. An agent acquires, heartbeats, and releases leases through MCP actions: `lock-acquire` and `lock-release` on the `storage_manage` tool, while inspecting lock states using `lock-status` on the `storage` tool. The lock indicates to other agents and users that an asset is undergoing active modification. Because the lock is advisory, concurrent writes still land safely in version history without corrupting file trees or throwing hard filesystem crashes.

### Granular Access Control and Ownership Transfer

Access is granted per organization, workspace and share through member roles. Developers can grant a smolagents connection scoped access to a single project workspace while keeping restricted files in separate workspaces.

For development teams and agencies building autonomous workflows for clients, Fast.io supports ownership transfer. An agent or developer can create an organization, build workspaces, configure sync pipelines, and transfer organizational ownership to a client with a claim link, handing over billing and primary data governance.

### Subscription Plans and Resource Limits

Monthly plans start with a 14-day free trial, which requires a credit card. Subscriptions are organized into three tiers to accommodate individual developers, growing teams, and large enterprise deployments:

| Plan | Monthly Pricing | Annual Billing | Included Seats | Workspace Storage | Single-File Upload | Monthly AI Credits |
| :--- | :--- | :--- | :--- | :--- | :--- | :--- |
| Starter | $9.99 monthly | $99 annually | 3 seats | 250 GB | 25 GB | 100,000 credits |
| Business | $49.99 monthly | $499 annually | 10 seats | 5 TB | 50 GB | 600,000 credits |
| Enterprise | $199.99 monthly | $1,999 annually | 30 seats included | 25 TB | 100 GB | 3,000,000 credits |

Annual billing options provide discounted rates for organizations committed to yearly deployments. Workspace storage, upload allowances, and member seats are included in each plan tier, and credits meter AI operations.

## Frequently asked questions

### How do I use MCP tools with smolagents?

You use MCP tools with smolagents by installing smolagents with MCP support and calling ToolCollection.from_mcp with your server configuration. ToolCollection discovers the exposed tools and translates them into native smolagents tools that you pass to CodeAgent or ToolCallingAgent instances.

### What is ToolCollection.from_mcp in smolagents?

ToolCollection.from_mcp is a class method in the Hugging Face smolagents library that dynamically loads tools from Model Context Protocol servers. It supports stdio, Streamable HTTP, and legacy SSE transports, handling connection lifecycles and tool registration.

### Can smolagents connect to remote MCP servers?

Yes. Smolagents connects to remote MCP servers by passing a dictionary with the server URL and transport type set to streamable-http to ToolCollection.from_mcp. You can pass authentication headers such as Bearer API keys directly in the connection dictionary.

### How do CodeAgents differ from ToolCallingAgents when using MCP tools?

CodeAgents generate and execute Python code blocks that invoke MCP tools, allowing filtering, data transformations, and iterative logic in a single model generation step. ToolCallingAgents rely on successive JSON tool calls that require multiple network round-trips for multi-step tasks.

### How do I authenticate smolagents with remote Fast.io MCP workspaces?

To authenticate smolagents with Fast.io, generate an API key in your account settings and supply it in the Authorization header as Bearer token in the server configuration dictionary passed to ToolCollection.from_mcp.

### Can smolagents search documents stored across Dropbox, Box, or OneDrive?

Yes. By synchronizing your Dropbox, Box, or OneDrive folders into a Fast.io workspace, documents are automatically indexed in the cloud. Smolagents can then execute hybrid search queries over the Fast.io MCP endpoint to retrieve relevant document passages with citations.

### Why is hybrid search better than raw document retrieval for smolagents?

Raw document retrieval pulls full multi-megabyte files across the network and floods the language model context window. Hybrid search combines full-text keywords with semantic vectors to return only the precise relevant paragraphs, preserving context capacity and reducing token usage.

## Sources

- [Anthropic](https://www.anthropic.com/news/model-context-protocol): Model Context Protocol provides an open standard for connecting AI systems with data sources, replacing fragmented integrations with a single protocol.

## About Fast.io

Fast.io provides shared workspaces where people and AI agents work on the same files, with built-in semantic search and citation-backed chat over what they hold. Agents reach it through a remote MCP server, a REST API at https://api.fast.io/current/, and a command line client published on npm as @vividengine/fastio-cli. MCP setup is at https://mcp.fast.io/docs: Claude and most MCP clients connect to https://mcp.fast.io/mcp/tools, ChatGPT to https://mcp.fast.io/mcp/operations, and coding agents to https://mcp.fast.io/mcp/code.
