Skip to main content

MCIClient Class

The MCIClient class is the main entry point for the MCI Python adapter. It provides methods for loading, filtering, and executing MCI tools from a JSON or YAML schema file.

Initialization

MCIClient(schema_file_path=None, env_vars=None, json_file_path=None, validating=False)

Initialize the MCI client with a schema file and optional environment variables. Parameters: *Either schema_file_path or json_file_path must be provided. Raises:
  • MCIClientError - If the schema file cannot be loaded or parsed
  • MCIClientError - If neither schema_file_path nor json_file_path is provided
Example:
Success Response: Returns an initialized MCIClient instance ready to use. Error Response:

Validating Mode

When validating=True is specified, the client operates in a special validation-only mode: What happens in validating mode:
  • ✅ Schema file is parsed and validated (JSON/YAML syntax, structure, types)
  • ✅ Schema version is checked for compatibility
  • ✅ Tool definitions are validated (required fields, execution types)
  • ✅ Toolset files are checked for existence (but not loaded)
  • ✅ MCP server configurations are validated (but servers are not contacted)
  • ✅ Read-only operations work normally (list_tools(), tools(), only(), without(), etc.)
What does NOT happen in validating mode:
  • ❌ No template resolution (placeholders like {{env.VAR}} are accepted as-is)
  • ❌ No MCP server connections or tool fetching
  • ❌ No toolset file loading (only existence is checked)
  • ❌ No file writes or cache directory creation
  • ❌ No network requests
  • ❌ Tool execution is blocked (raises MCIClientError)
Use cases for validating mode:
  • CI/CD validation: Check schema validity without requiring environment variables
  • IDE/Editor plugins: Validate schemas and provide autocomplete without side effects
  • Schema testing: Verify schema structure before deployment
  • Documentation generation: Parse schemas to generate tool documentation
  • Pre-deployment checks: Validate schemas before committing to version control
Example:

Methods

tools()

Get all available tools from the loaded schema. Method Signature:
Parameters: None Returns: Example:
Success Response:
Error Response: No errors - always returns a list (may be empty if no tools defined).

only()

Filter tools to include only specified tools by name. Method Signature:
Parameters: Returns: Example:
Success Response:
Error Response: No errors - returns empty list if no tools match the specified names.

without()

Filter tools to exclude specified tools by name. Method Signature:
Parameters: Returns: Example:
Success Response:
Error Response: No errors - returns all tools if specified names don’t exist.

tags()

Filter tools to include only those with at least one matching tag. Method Signature:
Parameters: Returns: Example:
Success Response:
Error Response: No errors - returns empty list if no tools have any of the specified tags. Notes:
  • Tags are case-sensitive and matched exactly as provided
  • Uses OR logic: a tool is included if it has ANY of the specified tags
  • Tools without tags are never included
  • Empty tag list returns empty result

withoutTags()

Filter tools to exclude those with any matching tag. Method Signature:
Parameters: Returns: Example:
Success Response:
Error Response: No errors - returns all tools if none have any of the specified tags. Notes:
  • Tags are case-sensitive and matched exactly as provided
  • Uses OR logic for exclusion: a tool is excluded if it has ANY of the specified tags
  • Tools without tags are always included (they don’t have the excluded tags)
  • Empty tag list returns all tools

toolsets()

Filter tools to include only those from specified toolsets. Method Signature:
Parameters: Returns: Example:
Success Response:
Error Response: No errors - returns empty list if no tools match the specified toolset names. Notes:
  • Only returns tools that were loaded from toolsets (not main schema tools)
  • Uses OR logic: a tool is included if it came from ANY of the specified toolsets
  • Toolset filtering respects schema-level filters (only tools registered by their toolset’s filter are included)
  • Empty toolset list returns no tools
  • Tools must have been loaded via the toolsets field in the main schema
  • The toolset_source field on each Tool indicates which toolset it came from

execute()

Execute a tool by name with the provided properties. Method Signature:
Parameters: Returns: Raises:
  • MCIClientError - If tool not found or execution fails with validation error
Example:
Success Response:
Error Response - Tool Not Found:
Error Response - Execution Error:
Error Response - Network Error:

list_tools()

List available tool names as strings. Method Signature:
Parameters: None Returns: Example:
Success Response:
Error Response: No errors - returns empty list if no tools defined.

get_tool_schema()

Get a tool’s input schema (JSON Schema format). Method Signature:
Parameters: Returns: Raises:
  • MCIClientError - If tool not found
Example:
Success Response:
Success Response - No Schema:
Error Response:

Data Models

MCISchema

Top-level MCI schema representing the complete MCI context file. Fields: Example:

Tool

Individual tool definition with name, description, input schema, and execution configuration. Fields: Example:

ExecutionResult

Result format returned from tool execution. Fields: Example - Success:
Example - Error:
Example - Text Content:
Example - File Content:

Metadata

Optional metadata about the MCI tool collection. Fields: Example:

Execution Configurations

HTTPExecutionConfig

Configuration for HTTP-based tool execution. Fields: Example - GET Request:
Example - POST Request with Authentication:

CLIExecutionConfig

Configuration for command-line tool execution. Fields: Example - Simple Command:
Example - Command with Flags:

FileExecutionConfig

Configuration for file reading and templating. Fields: Example - Read File with Templating:
Example - Read File Without Templating:

TextExecutionConfig

Configuration for simple text template execution. Fields: Example:
Execution Result:

Authentication Models

ApiKeyAuth

API Key authentication configuration. Fields: Example - Header-based:
Example - Query parameter:

BearerAuth

Bearer token authentication configuration. Fields: Example:

BasicAuth

Basic authentication (username/password) configuration. Fields: Example:

OAuth2Auth

OAuth2 authentication configuration. Fields: Example:

Error Handling

The MCI Python adapter provides consistent error handling across all operations.

Exception Types

MCIClientError

Raised by MCIClient methods for client-level errors. Common Causes:
  • Schema file not found or invalid
  • Tool not found
  • Invalid tool execution
Example:

ExecutionResult Error Format

Execution errors are returned as ExecutionResult objects with isError=True. Error Fields: Example Error Scenarios: HTTP Request Failed:
Connection Timeout:
CLI Command Failed:
File Not Found:
Template Variable Missing:
Path Validation Error:

Security: Path Validation

The MCI Python adapter includes built-in path validation to prevent unauthorized file system access. Default Behavior:
  • File and CLI execution are restricted to the schema file’s directory
  • Subdirectories of the schema directory are allowed
  • Paths outside the schema directory are blocked unless explicitly allowed
Configuration Options:
  1. Schema-level settings (applies to all tools):
  2. Tool-level settings (overrides schema-level):
Path Validation Behavior: Best Practices:
  • Keep enableAnyPaths disabled unless absolutely necessary
  • Use directoryAllowList for specific directories instead of enableAnyPaths
  • Validate user input before passing to tools that access files
  • Review tool configurations regularly for security implications

Error Handling Best Practices

Check isError Flag:
Try-Except for Client Errors:
Validate Tools Before Execution:

Complete Usage Example

Here’s a comprehensive example demonstrating all major features:

Template Syntax

MCI supports template placeholders for dynamic value substitution:
  • {{props.fieldName}} - Access properties passed to execute()
  • {{env.VARIABLE_NAME}} - Access environment variables
  • {{input.fieldName}} - Deprecated alias for props (use props instead)
Note: {{input.fieldName}} is supported for backward compatibility but is deprecated. Use {{props.fieldName}} in all new code. Example:
With execution:

Notes

  • All methods are synchronous (blocking) - execution waits for completion
  • Environment variables should be provided during initialization, not at execution time
  • Templates are processed before execution using a simple {{}} placeholder substitution system (not full Jinja2 syntax)
  • HTTP responses are automatically parsed as JSON when possible
  • CLI commands capture both stdout and stderr
  • File paths can be relative or absolute
  • Timeout values are in milliseconds
  • All string fields support template substitution unless explicitly disabled

LiteMcpClient Class

The LiteMcpClient class provides a lightweight integration with MCP (Model Context Protocol) servers using the official mcp package. It allows connecting to MCP tool servers via STDIO (e.g., uvx, npx) and HTTP/SSE endpoints.

Configuration Models

StdioCfg

Configuration for STDIO-based MCP servers (local servers via command-line). Fields: Example:

SseCfg

Configuration for HTTP/SSE-based MCP servers (web-based servers). Fields: Example:

ClientCfg

Complete configuration for the LiteMcpClient. Fields: Example:

Initialization

LiteMcpClient(cfg: ClientCfg)

Initialize the LiteMcpClient with configuration. Parameters: Example:

Usage

The LiteMcpClient must be used as an async context manager to properly manage the connection lifecycle. Example:

Methods

async list_tools() -> List[str]

List all available tools from the MCP server. Returns:
  • List[str] - List of tool names available on the server
Raises:
  • RuntimeError - If session is not initialized (client not used as context manager)
Example:

async call_tool(name: str, **arguments: Any) -> Any

Call a tool on the MCP server with the provided arguments. Parameters: Returns:
  • Any - The tool execution result from the server (typically containing content and metadata)
Raises:
  • RuntimeError - If session is not initialized (client not used as context manager)
Example:

Complete Examples

STDIO Example (uvx)

STDIO Example (npx)

HTTP Example

Error Handling

RuntimeError: Raised when attempting to use methods outside of context manager:
Connection Errors: Network or process errors are propagated from the underlying MCP client:

Notes

  • The LiteMcpClient uses the official mcp package for MCP protocol communication
  • STDIO transport merges environment variables from the configuration with the current process environment
  • HTTP transport uses Streamable HTTP, the modern replacement for SSE
  • All async operations must be called from within the context manager
  • The client automatically handles connection setup and teardown