MCP
Model Context Protocol integration, local execution boundaries, and stdio environment hardening controls.
#MCP Integration
The mAIvn SDK supports Model Context Protocol (MCP) servers as external tool providers. This enables integration with a wide ecosystem of MCP-compatible tools.
#Execution Security
The SDK calls MCP tools from your environment. Tool implementation code is never transferred to or executed on mAIvn servers.
- stdio transport: Launches a local process on your machine
- http transport: Connects from your process to the HTTP endpoint you configure. The tool code runs wherever that endpoint is hosted
The mAIvn server receives tool schemas and orchestrates which tools to call. The SDK performs the configured MCP call from your application environment.
#Import
from maivn import MCPAutoSetup, MCPServer#MCPServer
Configuration model for MCP server connections.
MCPServer(
name: str,
transport: Literal['http', 'stdio'] = 'stdio',
url: str | None = None,
command: str | None = None,
args: list[str] = [],
env: dict[str, str] | None = None,
inherit_env: bool = False,
inherit_env_allowlist: list[str] | None = None,
working_dir: str | None = None,
headers: dict[str, str] | None = None,
protocol_version: str = '2024-11-05',
client_name: str = 'maivn',
client_title: str = 'mAIvn',
client_version: str = '0.1.0',
tool_name_prefix: str | None = None,
tool_name_separator: str = '__',
default_tool_args: dict[str, Any] | None = None,
tool_defaults: dict[str, dict[str, Any]] | None = None,
injected_tool_args: dict[str, Any] | None = None,
model_visible_tool_args: list[str] | None = None,
max_calls_per_minute: int | None = None,
max_calls_per_day: int | None = None,
request_timeout_seconds: float | None = None,
stdio_response_timeout_seconds: float | None = None,
auto_setup: MCPAutoSetup | None = None,
)#Parameters
#Methods
The first list_tools() or call_tool() starts the transport and sends the MCP initialize request with protocol_version and the client fields. A stdio server needs command or auto_setup, and an http server needs url. Without them, the first call raises ValueError. The SDK discards a stdio server's stderr.
#Transport Types
#stdio Transport
Launches a local process and communicates via stdin/stdout.
mcp_server = MCPServer(
name='local_tools',
transport='stdio',
command='python',
args=['-m', 'my_mcp_server'],
env={'API_KEY': 'secret'},
stdio_response_timeout_seconds=30, # Optional: avoid hanging forever
)For hardened deployments, keep stdio inheritance tight while still allowing the runtime to launch:
mcp_server = MCPServer(
name='local_tools',
transport='stdio',
command='python',
args=['-m', 'my_mcp_server'],
inherit_env_allowlist=['OPENAI_API_KEY'],
env={'API_KEY': 'explicit-token'},
stdio_response_timeout_seconds=30,
)By default, maivn carries only a small runtime baseline such as PATH so the subprocess can start. Add provider credentials through env or inherit_env_allowlist explicitly. Set inherit_env=True only for trusted subprocesses that need the full parent shell environment.
#http Transport
Connects to an HTTP endpoint. The SDK posts JSON-RPC requests, reads either a JSON or a server-sent-event response, and repeats the Mcp-Session-Id header the server returns.
mcp_server = MCPServer(
name='remote_tools',
transport='http',
url='https://mcp.example.com/api',
headers={'Authorization': 'Bearer token'},
)#MCPAutoSetup
Auto-setup configuration for uvx-based MCP servers.
MCPAutoSetup(
provider: Literal['uvx'] = 'uvx',
package: str,
args: list[str] = [],
with_packages: list[str] = [],
env: dict[str, str] | None = None,
uvx_command: str | None = None,
)#Parameters
#Example
mcp_server = MCPServer(
name='filesystem',
transport='stdio',
auto_setup=MCPAutoSetup(
package='your-mcp-server-package',
args=['--config', '/data/server-config.json'],
),
)Replace the package and arguments with the server you have selected. This shape resolves to uvx your-mcp-server-package --config /data/server-config.json. with_packages=["dependency==version"] adds uvx --with requirements when needed.
#Registering MCP Servers
Register MCP servers with an Agent. Swarm has no MCP registration methods, so register servers on the member agents. Registering a second server with a name that is already registered raises ValueError.
from maivn import Agent, MCPServer
agent = Agent(name='mcp_agent', api_key='...')
# Single server
agent.register_mcp_servers(MCPServer(
name='tools',
transport='stdio',
command='my-mcp-server',
))
# Multiple servers
agent.register_mcp_servers([
MCPServer(name='fs', transport='stdio', command='fs-server'),
MCPServer(name='api', transport='http', url='https://api.example.com'),
])#Tool Name Mapping
MCP tools are registered with prefixed names to avoid conflicts:
# MCP server exposes: read_file, write_file
# With default settings (prefix=server name, separator='__'):
# Tools become: tools__read_file, tools__write_file
mcp_server = MCPServer(
name='tools',
tool_name_prefix='fs', # Custom prefix
tool_name_separator='_', # Custom separator
)
# Tools become: fs_read_file, fs_write_file#Disable Prefix
mcp_server = MCPServer(
name='tools',
tool_name_prefix='', # Empty string = no prefix
)
# Tools keep original names: read_file, write_file#Default Arguments
#Global Defaults
Apply default arguments to all MCP tools:
mcp_server = MCPServer(
name='api',
transport='http',
url='https://api.example.com',
default_tool_args={
'timeout': 30,
'format': 'json',
},
)#Per-Tool Defaults
Apply defaults to specific tools:
mcp_server = MCPServer(
name='fs',
transport='stdio',
command='fs-server',
tool_defaults={
'read_file': {'encoding': 'utf-8'},
'write_file': {'create_dirs': True},
},
)Per-tool defaults override global defaults. The current compiler also treats these values as injected arguments, which win over model-supplied values. Explicit injected_tool_args has the highest priority. Configured arguments and recognized credential argument names are hidden from the model-facing schema by default. model_visible_tool_args can keep named arguments visible, but does not change the precedence of injected values.
#Renaming and reshaping tools
The MCP compiler does not use the server's advertised output schema, and local add_tool and add_toolset do not accept override arguments. Use an application wrapper when you need a different name, output contract or argument rewriting.
#Rate Limiting
max_calls_per_minute and max_calls_per_day limit tool calls to one MCPServer. Both are optional, and each must be at least 1 or construction raises ValueError.
- Per minute. When the last 60 seconds already hold that many calls, the next call waits for a free slot, then goes through. Concurrent callers queue in order.
- Per day. When the last 24 hours already hold that many calls, the next call raises
MCPRuntimeErrorwithout contacting the server.
Calls are counted in your process, per MCPServer object, and only tool calls count; discovery does not. A restart resets the counts, and separate processes do not share them, so keep the upstream server's own quota as well.
#Retries and soft errors
The transport does not scan response bodies for soft errors or retry a call. Put retries in the MCP server or your application when you need them.
#Error Handling
HTTP failures propagate through HTTPX. JSON-RPC error responses raise MCPRuntimeError, a RuntimeError subclass that maivn does not export, so catch RuntimeError. Missing or malformed result objects can raise TypeError. A stdio response wait can raise TimeoutError when an explicit timeout expires. A stdio server that exits mid-request raises RuntimeError.
#Lifecycle
#Listing Servers
servers = agent.list_mcp_servers()
for server in servers:
print(f'{server.name}: {server.transport}')#Closing Servers
Call agent.close() to stop every MCP server registered on the agent. A stdio process is terminated and an HTTP session is closed. Each server starts again on its next use. close() is safe to call twice. It also releases the connection pools of a client the agent created itself, and it never closes a Client you passed in.
agent.close()Swarm.close() does not close member agents, so call close() on each member agent that has MCP servers. You can also close one server with server.close(). close_mcp_servers() is not available.
#Complete Example
Supply the path to your installed filesystem MCP server before running this example.
from maivn import Agent, MCPServer
from maivn.messages import HumanMessage
# Create agent
agent = Agent(
name='file_agent',
description='Agent with file system access',
system_prompt='You can read and write files.',
api_key='your-api-key',
)
# Register filesystem MCP server
agent.register_mcp_servers(MCPServer(
name='fs',
transport='stdio',
command='python',
args=['path/to/your_filesystem_mcp_server.py'],
tool_name_prefix='file',
stdio_response_timeout_seconds=30,
))
# Use the agent (MCP tools are available)
response = agent.invoke([
HumanMessage(content='List files in the current directory')
])
# Clean up
agent.close()#See Also
- Connecting MCP Servers - Concept guide: the trust boundary, choosing a transport, auth model
- MCP Examples - Runnable stdio, HTTP, multi-server, and
uvxsetups - Agent -
register_mcp_servers()method - Tools Guide - Tool patterns
- MCP Specification - Protocol details