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

#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 = '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

ParameterTypeDefaultDescription
namestrRequiredLogical name for the MCP server. Must not be empty
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. Ignored when inherit_env_allowlist is non-empty
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_namestr'maivn'Identifier sent to the MCP server during initialization
client_titlestr'mAIvn'Friendly client title sent during MCP initialization
client_versionstr'0.1.0'Client 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. Must not be empty
default_tool_argsdict | NoneNoneDefault args for all tools
tool_defaultsdict[str, dict] | NoneNonePer-tool default arguments
injected_tool_argsdict | NoneNoneArguments the SDK always supplies for every tool. The model never authors them
model_visible_tool_argslist[str] | NoneNoneArgument names to keep visible to the model even when they would otherwise be hidden
max_calls_per_minuteint | NoneNoneMost tool calls to this server in any 60 seconds. A call over the limit waits for a free slot. Must be at least 1
max_calls_per_dayint | NoneNoneMost tool calls to this server in any 24 hours. A call over the limit raises MCPRuntimeError without contacting the server. Must be at least 1
request_timeout_secondsfloat | NoneNoneHTTP timeout override. The HTTP transport uses 30 seconds when unset
stdio_response_timeout_secondsfloat | NoneNoneTimeout for stdio responses (None = wait indefinitely)
auto_setupMCPAutoSetup | NoneNoneAuto-setup configuration

#Methods

MethodPurpose
list_tools()Discovers the server's tools over its transport and returns the raw tool objects.
call_tool(tool_name, arguments)Runs one tool by its raw MCP name and returns the result object.
build_tool_name(mcp_tool_name)Returns the public tool name, which joins the prefix and the raw name with the separator and replaces - and spaces with _.
close()Closes the transport. A stdio process gets a terminate signal and is killed if it has not exited after 2 seconds.

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.

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

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

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.

#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 MCPRuntimeError without 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

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

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

Python
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