Skip to content

Documentation navigation

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

Python
from maivn import MCPAutoSetup, MCPServer, MCPSoftErrorHandling, ToolOverride

#MCPServer

Configuration model for MCP server connections.

Plain text
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 = SDK_DEFAULT,
    client_title: str = SDK_DEFAULT,
    client_version: str = SDK_DEFAULT,
    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,
    tool_overrides: dict[str, ToolOverride] | 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,
    raise_on_tool_error: bool = False,
    auto_setup: MCPAutoSetup | None = None,
    soft_error_handling: MCPSoftErrorHandling | None = None,
)

#Parameters

ParameterTypeDefaultDescription
namestrRequiredLogical name for the MCP server
transportLiteral['http', 'stdio']'stdio'Communication protocol
urlstr | NoneNoneHTTP endpoint (required for http transport)
commandstr | NoneNoneCommand to launch stdio server
argslist[str][]Arguments for stdio server
envdict[str, str] | NoneNoneEnvironment variables
inherit_envboolFalseWhether stdio servers inherit the full parent process environment
inherit_env_allowlistlist[str] | NoneNoneOptional parent env vars to inherit with the minimal runtime env
working_dirstr | NoneNoneWorking directory for stdio server
headersdict[str, str] | NoneNoneHTTP headers
protocol_versionstr'2024-11-05'MCP protocol version
client_namestrSDK defaultIdentifier sent to the MCP server during initialization
client_titlestrSDK defaultFriendly client title sent during MCP initialization
client_versionstrSDK defaultClient version sent during MCP initialization
tool_name_prefixstr | NoneNonePrefix for tool names. When unset, the effective prefix falls back to name
tool_name_separatorstr'__'Separator between prefix and name
default_tool_argsdict | NoneNoneDefault args for all tools
tool_defaultsdict[str, dict] | NoneNonePer-tool default arguments
tool_overridesdict[str, ToolOverride] | NoneNoneCompatibility field; not applied during compilation
max_calls_per_minuteint | NoneNoneCompatibility field; no rate limiting
max_calls_per_dayint | NoneNoneCompatibility field; no rate limiting
request_timeout_secondsfloat | NoneNoneHTTP timeout override
stdio_response_timeout_secondsfloat | NoneNoneTimeout for stdio responses (None = wait indefinitely)
raise_on_tool_errorboolFalseCompatibility field; not applied
auto_setupMCPAutoSetup | NoneNoneAuto-setup configuration
soft_error_handlingMCPSoftErrorHandling | NoneNoneCompatibility field; no scanning or retry

#Transport Types

#stdio Transport

Launches a local process and communicates via stdin/stdout.

Python
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:

Python
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.

Python
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.

Plain text
MCPAutoSetup(
    provider: Literal['uvx'] = 'uvx',
    package: str,
    args: list[str] = [],
    with_packages: list[str] = [],
    env: dict[str, str] | None = None,
    working_dir: str | None = None,
    uvx_command: str | None = None,
)

#Parameters

ParameterTypeDefaultDescription
providerLiteral['uvx']'uvx'Installer (currently only uvx)
packagestrRequiredPackage name to install/run
argslist[str][]Arguments to pass to the server
envdict[str, str] | NoneNoneEnvironment variables
working_dirstr | NoneNoneCompatibility field; set the directory on MCPServer
uvx_commandstr | NoneNoneOverride uvx binary name. When unset, the SDK resolves to 'uvx' at runtime

#Example

Python
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 or Swarm:

Python
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:

Python
# 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

Python
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:

Python
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:

Python
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.

#Tool Overrides

ToolOverride and MCPServer.tool_overrides are accepted compatibility models. The current MCP compiler does not apply them, validate unknown override keys, or use the server's advertised output schema. Local add_tool and add_toolset also do not accept override arguments. Use an application wrapper when you need a different name, output contract, or argument transformation.

#Rate Limiting

max_calls_per_minute and max_calls_per_day are retained values with no active rate limiter or pacing implementation. Enforce upstream quotas in your MCP server or application.

#Soft Error Handling

MCPSoftErrorHandling retains enabled=False, max_retries=1, initial_backoff_seconds=5.0, max_backoff_seconds=60.0, and keys=['Note', 'Information', 'Error Message']. Negative max_retries is rejected. The current transport does not consume this config, scan soft-error keys, or retry.

#Error Handling

HTTP failures propagate through HTTPX. JSON-RPC error responses raise MCPRuntimeError; missing or malformed result objects can raise TypeError. raise_on_tool_error is a compatibility field and does not change this behavior. A stdio response wait can raise TimeoutError when an explicit timeout expires.

#Lifecycle

#Listing Servers

Python
servers = agent.list_mcp_servers()
for server in servers:
    print(f'{server.name}: {server.transport}')

#Closing Servers

Close servers directly. Agent.close() and Swarm.close() are currently no-ops; close_mcp_servers() is not available.

Python
for server in agent.list_mcp_servers():
    server.close()
agent.client.close()  # Only when this application owns the client.

#Complete Example

Supply the path to your installed filesystem MCP server before running this example.

Python
from maivn import Agent, MCPServer, MCPAutoSetup
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
for server in agent.list_mcp_servers():
    server.close()
agent.client.close()

#See Also