sdk-python icon indicating copy to clipboard operation
sdk-python copied to clipboard

[FEATURE] Support for multiple MCP servers (and loading from config file)

Open jer96 opened this issue 1 year ago • 14 comments

Overview

Add support for loading MCP server configurations from a JSON config file, allowing users to define multiple MCP servers declaratively instead of programmatically. This extends the existing experimental agent_config.py to support an mcp_servers field that creates and manages MCPClient instances automatically.

Note: Multiple MCP servers and automatic lifecycle management already work programmatically (see tests_integ/mcp/test_mcp_tool_provider.py::test_mcp_client_multiple_servers). This feature request is specifically about configuration file support.

Implementation Requirements

1. Extend Agent Config Schema (src/strands/experimental/agent_config.py)

Add mcp_servers to the existing AGENT_CONFIG_SCHEMA JSON schema. The configuration format should be compatible with the Claude Desktop / Cursor / VS Code mcpServers convention where possible.

Target config format:

{
  "name": "my_agent",
  "model": "us.anthropic.claude-3-5-sonnet-20241022-v2:0",
  "prompt": "You are a helpful assistant.",
  "tools": ["strands_tools.file_read"],
  "mcp_servers": {
    "aws_docs": {
      "command": "uvx",
      "args": ["awslabs.aws-documentation-mcp-server@latest"],
      "env": { "AWS_PROFILE": "default" },
      "prefix": "aws",
      "startup_timeout": 30,
      "tool_filters": {
        "allowed": ["search_.*"],
        "rejected": ["dangerous_tool"]
      }
    },
    "remote_service": {
      "transport": "sse",
      "url": "http://localhost:8000/sse",
      "headers": {
        "Authorization": "Bearer token123"
      },
      "prefix": "remote"
    },
    "http_service": {
      "transport": "streamable-http",
      "url": "http://localhost:8000/mcp",
      "headers": {},
      "prefix": "http"
    }
  }
}

2. Create MCP Config Module (src/strands/tools/mcp/mcp_config.py)

Create a new module that handles parsing MCP server configuration and creating MCPClient instances.

Key components:

  • Transport type detection: Infer transport from config (default to stdio if command is present, otherwise infer from url or explicit transport field)
  • Transport types to support:
    • stdio — uses mcp.client.stdio.stdio_client with StdioServerParameters
    • sse — uses mcp.client.sse.sse_client
    • streamable-http — uses mcp.client.streamable_http.streamablehttp_client
  • Config-to-MCPClient mapping: Convert each server config entry into an MCPClient instance with the appropriate transport callable

Per-server configuration options:

Field Type Required Description
command string For stdio Command to run the MCP server
args string[] No Arguments for the command
env object No Environment variables for the subprocess
cwd string No Working directory for stdio subprocess
transport string No Transport type: "stdio", "sse", "streamable-http" (auto-detected if omitted)
url string For sse/http URL of the remote MCP server
headers object No HTTP headers for sse/http transports
prefix string No Prefix for tool names to avoid collisions
startup_timeout int No Timeout for server initialization (default: 30)
tool_filters object No Tool filter config with allowed and rejected arrays of string/regex patterns

3. Integrate with config_to_agent

Update config_to_agent() in agent_config.py to:

  1. Parse the mcp_servers field from config
  2. Create MCPClient instances using the new config module
  3. Append MCPClient instances to the tools list passed to Agent()
  4. Let existing ToolProvider handling in ToolRegistry.process_tools() manage lifecycle

4. Also Provide Standalone Config Loading

In addition to config_to_agent integration, provide a standalone function to load MCP clients from config for users who want to use them independently:

from strands.tools.mcp import MCPClient
from strands.tools.mcp.mcp_config import load_mcp_clients_from_config

# Load from file
clients = load_mcp_clients_from_config("mcp_config.json")

# Or from dict
clients = load_mcp_clients_from_config({
    "aws_docs": {
        "command": "uvx",
        "args": ["awslabs.aws-documentation-mcp-server@latest"]
    }
})

# Use with agent
agent = Agent(tools=list(clients.values()))

5. Testing

Unit tests (tests/strands/tools/mcp/test_mcp_config.py):

  • Config parsing and validation for each transport type
  • Transport type auto-detection logic
  • Tool filter parsing (string literals → exact match, regex patterns)
  • Error handling for invalid configs
  • MCPClient creation with correct parameters

Unit tests (tests/strands/experimental/test_agent_config.py):

  • Extend existing tests for config_to_agent with mcp_servers field

Integration tests (tests_integ/mcp/test_mcp_config.py):

  • Load MCP servers from config file using existing echo_server.py
  • Verify tools are loaded and callable via agent
  • Multiple server config loading

Files to Create/Modify

File Action Description
src/strands/tools/mcp/mcp_config.py Create MCP config parsing and MCPClient factory
src/strands/tools/mcp/__init__.py Modify Export new config module
src/strands/experimental/agent_config.py Modify Add mcp_servers to schema and processing
tests/strands/tools/mcp/test_mcp_config.py Create Unit tests for config module
tests/strands/experimental/test_agent_config.py Modify Add tests for mcp_servers in agent config
tests_integ/mcp/test_mcp_config.py Create Integration tests
AGENTS.md Modify Update directory structure

Acceptance Criteria

  • [ ] Users can define multiple MCP servers in a JSON config file
  • [ ] Config supports stdio, SSE, and streamable-http transport types
  • [ ] Transport type is auto-detected when not explicitly specified
  • [ ] config_to_agent() correctly creates agents with MCP tools from config
  • [ ] Standalone load_mcp_clients_from_config() function works independently
  • [ ] Per-server options work: prefix, startup_timeout, tool_filters, env, headers
  • [ ] Tool filters support string literals and regex patterns in config
  • [ ] Invalid configurations produce clear error messages with JSON schema validation
  • [ ] Unit tests cover all config parsing paths and edge cases
  • [ ] Integration tests verify end-to-end MCP tool usage from config
  • [ ] Existing MCP programmatic usage (Agent(tools=[mcp_client])) is unaffected

Assumptions

  1. JSON only — No YAML/TOML support needed for now (per maintainer decision)
  2. Skip graceful failures — #1481 (fail-open strategy) is deferred; a single server failure will fail agent init as-is
  3. No environment variable interpolation — Config values are taken as-is (env passthrough via env field for stdio only)
  4. Experimental — This feature lives under experimental/agent_config.py and is subject to API changes
  5. No workflow changes — No GitHub Actions modifications required

Prior Art & References

  • Closed PR #623: Prior implementation attempt by @JackYPCOnline with mcp_from_config.py — can reference for patterns
  • Docs PR #718: Design doc for broader MCP integration by @mkmeral — config loading is identified as P1 gap
  • Issue #1481: Graceful MCP server startup failures — deferred, can be layered on later
  • Claude Desktop config format: Industry-standard mcpServers JSON format
  • Existing patterns: agent_config.py for JSON schema validation, MCPClient for transport handling

Notes for Future Improvement

  • Consider adding YAML support in a follow-up
  • Consider environment variable interpolation (e.g., ${ENV_VAR}) for sensitive values
  • Consider fail_open option when #1481 is implemented
  • The AGENTS.md directory structure should be updated to reflect the new mcp_config.py file
  • README.md MCP section could be updated with config file example

jer96 avatar Jul 16 '25 13:07 jer96

/strands

Unshure avatar Dec 30 '25 20:12 Unshure

Repository Analysis & Clarifying Questions

Repository Analysis

I've analyzed the current implementation and found that multiple MCP servers and lifecycle management are already supported! The gap is specifically around configuration file support.

Current Capabilities ✅

Multiple MCP Server Support:

# This already works!
client1 = MCPClient(
    lambda: stdio_client(StdioServerParameters(command="uvx", args=["server1"])),
    prefix="server1"
)
client2 = MCPClient(
    lambda: stdio_client(StdioServerParameters(command="uvx", args=["server2"])),
    prefix="server2"
)

agent = Agent(tools=[client1, client2])

Automatic Lifecycle Management:

  • MCPClient implements the ToolProvider interface
  • Lifecycle is automatically managed when clients are passed to Agent
  • Cleanup happens via consumer tracking (add_consumer/remove_consumer)
  • See test: tests_integ/mcp/test_mcp_tool_provider.py::test_mcp_client_multiple_servers

What's Missing ❌

Configuration file support for MCP servers - Users currently must define MCP clients programmatically.

There is an experimental agent_config.py that supports loading agents from JSON, but it does not support MCP configuration.


Clarifying Questions

1. Configuration File Format & Location

Q1.1: What configuration file format should be used?

  • JSON (matching existing agent_config.py)?
  • YAML?
  • TOML?
  • Other format?

Q1.2: Where should MCP configuration be located?

  • Integrated into the existing agent config structure?
  • Separate MCP-specific config file?
  • Support both approaches?

2. Configuration Schema

Q2.1: Should MCP configuration be part of the agent config, or separate?

Option A - Integrated Agent Config:

{
  "name": "my_agent",
  "model": "claude-3-5-sonnet-20241022",
  "mcp_servers": [
    {
      "name": "aws_docs",
      "transport": {
        "type": "stdio",
        "command": "uvx",
        "args": ["awslabs.aws-documentation-mcp-server@latest"]
      },
      "prefix": "aws",
      "startup_timeout": 30
    }
  ]
}

Option B - Separate MCP Config:

{
  "mcp_servers": [
    {
      "name": "aws_docs",
      "transport": { "type": "stdio", "command": "uvx", "args": [...] },
      "prefix": "aws"
    }
  ]
}

Which approach is preferred?

3. Transport Types

Q3.1: Which MCP transport types should be supported in configuration?

  • stdio (command-line based servers)
  • SSE (Server-Sent Events / HTTP streaming)
  • WebSocket
  • All of the above?

Q3.2: For each transport type, what parameters need to be configurable?

Example for stdio:

{
  "transport": {
    "type": "stdio",
    "command": "python",
    "args": ["server.py"],
    "env": {...}  // Should environment variables be configurable?
  }
}

4. MCP Client Configuration Options

Q4.1: Which MCPClient options should be configurable?

  • ✅ prefix (for tool name prefixing)?
  • ✅ startup_timeout?
  • ✅ tool_filters (allowed/rejected patterns)?
  • elicitation_callback (probably not, requires code)?

Q4.2: How should tool filters be specified in config?

Example:

{
  "tool_filters": {
    "allowed": ["echo", "list_.*"],  // String literals or regex patterns
    "rejected": ["dangerous_tool"]
  }
}

5. Environment Variables & Dynamic Configuration

Q5.1: Should the configuration support environment variable interpolation?

Example:

{
  "transport": {
    "type": "stdio",
    "command": "${MCP_SERVER_COMMAND}",
    "args": ["${MCP_SERVER_ARGS}"]
  }
}

Q5.2: Should paths in configuration support relative paths, and if so, relative to what?

6. Scope & Testing

Q6.1: Should this implementation:

  • Extend the existing experimental agent_config.py?
  • Create a new module for MCP configuration?
  • Both?

Q6.2: Are there specific MCP servers you'd like to test with?

Q6.3: Should example configurations be provided in documentation?

7. Error Handling

Q7.1: How should configuration validation errors be reported?

  • Fail fast during config loading?
  • Detailed validation messages?

Q7.2: How should MCP server startup failures be handled?

  • Fail agent initialization?
  • Skip the failing server and continue with others?
  • Configurable behavior?

Recommendation

Based on the repository structure, I recommend:

  1. Extend src/strands/experimental/agent_config.py to support MCP configuration
  2. Start with stdio transport as it's most commonly used
  3. Use JSON format to match existing config pattern
  4. Integrate into agent config for unified configuration
  5. Support basic configuration options: prefix, startup_timeout, tool_filters

This keeps the implementation focused and aligned with existing patterns.

github-actions[bot] avatar Dec 30 '25 20:12 github-actions[bot]

https://github.com/strands-agents/sdk-python/pull/623

mkmeral avatar Jan 26 '26 17:01 mkmeral

Refinement notes:

  • We need to agree on a format (or maybe support multiple? :) )
  • We need to agree Strands specific options
  • We should probably fix this beforehand https://github.com/strands-agents/sdk-python/issues/1481

mkmeral avatar Jan 26 '26 17:01 mkmeral

Chiming in as a consumer, I think would be excellent if it could support multiple mcp servers, users could provide a list of mcp server urls to connect via http.

Something like:

{
  "model": "us.anthropic.claude-3-5-sonnet-20241022-v2:0",
  "prompt": "You are a coding assistant. Help users write, debug, and improve their code. You have access to file operations and can execute shell commands when needed.",
  "tools": ["strands_tools.file_read", "strands_tools.editor", "strands_tools.shell"], 
  "mcp_servers": [
     {   # dict to keep this extensible
         "url": "" 
     }
   ]
}

However, these items immediately come to mind, would need to brainstorm:

  • How would a user pass in different headers to different MCP servers?
  • What if a user wants to filter x tools from x server so the agent only knows about x tools at runtime, even when connected to multiple servers.

For this second bit, we are currently doing this manually by loading all of the tools from servers and then filtering only the ones that have been configured for the agent in code.

I think the second bit may be a different feature altogether, unless something like this could be done:

  "mcp_servers": [
     {
         "url": "my-store-server-a.com/mcp",
         "tools": [
          "load_invoices",
          "build_order"
         ]
     }
   ]

MannyDiera avatar Feb 20 '26 00:02 MannyDiera

/strands review the latest comments and refine this issue

Unshure avatar Apr 02 '26 13:04 Unshure

Issue Refinement Summary

Based on the latest comments and repository analysis, here's the refined scope for this feature:

Current State ✅

Multiple MCP servers and lifecycle management already work programmatically. The gap is specifically configuration file support.

Key Decisions Needed

Based on @mkmeral's notes and @MannyDiera's feedback:

Decision Recommendation Rationale
Format JSON Matches existing agent_config.py pattern
Location Extend experimental/agent_config.py Unified configuration approach
Transports stdio, sse, streamable-http Cover all common use cases

Proposed Configuration Schema

{
  "name": "my_agent",
  "model": "us.anthropic.claude-3-5-sonnet-20241022-v2:0",
  "prompt": "You are a helpful assistant.",
  "tools": ["strands_tools.file_read"],
  "mcp_servers": [
    {
      "name": "aws_docs",
      "transport": "stdio",
      "command": "uvx",
      "args": ["awslabs.aws-documentation-mcp-server@latest"],
      "prefix": "aws",
      "startup_timeout": 30,
      "tool_filter": {
        "allowed": ["search_.*"],
        "rejected": ["dangerous_tool"]
      }
    },
    {
      "name": "remote_service",
      "transport": "sse",
      "url": "http://localhost:8000/sse",
      "headers": {
        "Authorization": "Bearer ${MCP_AUTH_TOKEN}"
      }
    }
  ]
}

Strands-Specific Options (per server)

Option Type Description
name string Server identifier (required)
prefix string Prefix for tool names to avoid collisions
startup_timeout int Timeout for server initialization
tool_filter object Filter tools with allowed/rejected patterns
headers object Per-server HTTP headers (for SSE/HTTP transports)

Dependencies

⚠️ Blocking: #1481 - Graceful MCP server startup failures

  • When loading multiple servers from config, a single failure shouldn't break the entire agent
  • Recommend implementing #1481 first or in conjunction

Questions for Maintainers

  1. Should we support YAML in addition to JSON?
  2. Should mcp_servers be in agent config or separate file (or both)?
  3. Any additional Strands-specific options needed beyond what MCPClient already supports?

Next Steps

  1. Get alignment on the schema above
  2. Implement #1481 (graceful failures)
  3. Extend agent_config.py with MCP support
  4. Add documentation and examples

github-actions[bot] avatar Apr 02 '26 13:04 github-actions[bot]

@Unshure fyi https://github.com/strands-agents/docs/pull/718

mkmeral avatar Apr 02 '26 13:04 mkmeral

/strands

  1. Just json for now
  2. it can be in agent config
  3. For now no

We can also skip 1481 for now

Unshure avatar Apr 10 '26 14:04 Unshure

Task Refinement Complete

Summary

The issue has been refined and updated with a comprehensive implementation description. Here's what was accomplished:

Analysis Results

  • Multiple MCP servers and lifecycle management already work programmatically
  • The actual gap is configuration file support for defining MCP servers declaratively
  • Prior attempt in PR #623 (closed) provides useful patterns to reference
  • Design doc PR #718 in strands-agents/docs confirms config loading as a P1 gap

Decisions Made (from maintainer input)

Decision Answer
Config format JSON only for now
Config location Integrated into existing agent config
Additional Strands-specific options None beyond MCPClient defaults
Graceful failures (#1481) Deferred / skipped for now

Implementation Scope

  • New file: src/strands/tools/mcp/mcp_config.py — MCP config parser & MCPClient factory
  • Modify: src/strands/experimental/agent_config.py — Add mcp_servers to schema
  • Modify: src/strands/tools/mcp/__init__.py — Export new module
  • Tests: Unit tests + integration tests using existing echo_server
  • Transport support: stdio, SSE, streamable-http

Readiness Assessment

✅ This issue is ready for implementation. It is well-scoped for a single developer and a single PR. The implementation path is clear, building on existing patterns in agent_config.py and MCPClient.

github-actions[bot] avatar Apr 10 '26 14:04 github-actions[bot]

/strands implement

Unshure avatar Apr 10 '26 14:04 Unshure

Unable to create pull request via API. You can create it manually by clicking here.

github-actions[bot] avatar Apr 10 '26 14:04 github-actions[bot]

Loading from JSON config matters most when teams want their MCP server set per-environment without code change. The shape we landed on internally: env-overlays in the JSON ({"mcp_servers": {"_base": {...}, "prod": {...overrides...}}}) so dev/stage/prod swap server lists declaratively.

Two gotchas worth designing in: lifecycle ordering when one MCP server depends on another being up first, and credential resolution (env vars vs secrets manager) so the JSON itself is committable without leaking secrets.

If the implementation lands without these the config file pattern still works, just with a thicker user-side wrapper.

MukundaKatta avatar May 10 '26 15:05 MukundaKatta

Closing as completed: multiple MCP servers with config-file loading shipped in both SDKs as load_servers — Python in #3053 and TypeScript in #2947, both supporting the mcpServers JSON format with env-var interpolation, disabled, and per-server error tolerance. Docs: https://strandsagents.com/latest/documentation/docs/user-guide/concepts/tools/mcp-tools/

yonib05 avatar Jul 15 '26 14:07 yonib05