MCIClient Class
TheMCIClient 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:
| Name | Type | Required | Description |
|---|---|---|---|
schema_file_path | str | Conditional* | Path to the MCI schema file (.json, .yaml, or .yml) |
env_vars | dict[str, Any] | No | Environment variables for template substitution (default: {}) |
json_file_path | str | Conditional* | DEPRECATED. Use schema_file_path instead. Kept for backward compatibility. |
validating | bool | No | Enable pure schema validation mode without loading MCP servers, toolsets, or resolving templates. Tool execution is disabled in this mode. (default: False) |
schema_file_path or json_file_path must be provided.
Raises:
MCIClientError- If the schema file cannot be loaded or parsedMCIClientError- If neitherschema_file_pathnorjson_file_pathis provided
MCIClient instance ready to use.
Error Response:
Validating Mode
Whenvalidating=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.)
- ❌ 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)
- 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
Methods
tools()
Get all available tools from the loaded schema.
Method Signature:
| Type | Description |
|---|---|
list[Tool] | List of all Tool objects in the schema |
only()
Filter tools to include only specified tools by name.
Method Signature:
| Name | Type | Required | Description |
|---|---|---|---|
tool_names | list[str] | Yes | List of tool names to include |
| Type | Description |
|---|---|
list[Tool] | Filtered list of Tool objects matching the specified names |
without()
Filter tools to exclude specified tools by name.
Method Signature:
| Name | Type | Required | Description |
|---|---|---|---|
tool_names | list[str] | Yes | List of tool names to exclude |
| Type | Description |
|---|---|
list[Tool] | Filtered list of Tool objects excluding the specified names |
tags()
Filter tools to include only those with at least one matching tag.
Method Signature:
| Name | Type | Required | Description |
|---|---|---|---|
tags | list[str] | Yes | List of tags to filter by (OR logic - tool must have at least one matching tag) |
| Type | Description |
|---|---|
list[Tool] | Filtered list of Tool objects that have at least one of the specified tags |
- 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:
| Name | Type | Required | Description |
|---|---|---|---|
tags | list[str] | Yes | List of tags to exclude (OR logic - tool is excluded if it has any matching tag) |
| Type | Description |
|---|---|
list[Tool] | Filtered list of Tool objects that do NOT have any of the specified tags |
- 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:
| Name | Type | Required | Description |
|---|---|---|---|
toolset_names | list[str] | Yes | List of toolset names to include (OR logic - tool is included if it came from any matching toolset) |
| Type | Description |
|---|---|
list[Tool] | Filtered list of Tool objects from the specified toolsets |
- 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
toolsetsfield in the main schema - The
toolset_sourcefield on each Tool indicates which toolset it came from
execute()
Execute a tool by name with the provided properties.
Method Signature:
| Name | Type | Required | Description |
|---|---|---|---|
tool_name | str | Yes | Name of the tool to execute |
properties | dict[str, Any] | No | Properties/parameters to pass to the tool (default: {}) |
| Type | Description |
|---|---|
ExecutionResult | Result object with success/error status and content |
MCIClientError- If tool not found or execution fails with validation error
list_tools()
List available tool names as strings.
Method Signature:
| Type | Description |
|---|---|
list[str] | List of tool names (strings) |
get_tool_schema()
Get a tool’s input schema (JSON Schema format).
Method Signature:
| Name | Type | Required | Description |
|---|---|---|---|
tool_name | str | Yes | Name of the tool |
| Type | Description |
|---|---|
dict[str, Any] | Tool’s input schema as a dictionary (or empty dict if no schema) |
MCIClientError- If tool not found
Data Models
MCISchema
Top-level MCI schema representing the complete MCI context file. Fields:| Field | Type | Required | Description |
|---|---|---|---|
schemaVersion | str | Yes | Schema version (e.g., “1.0”) |
metadata | Metadata | No | Optional metadata about the tool collection |
tools | list[Tool] | Yes | List of tool definitions |
Tool
Individual tool definition with name, description, input schema, and execution configuration. Fields:| Field | Type | Required | Description |
|---|---|---|---|
name | str | Yes | Unique identifier for the tool |
annotations | Annotations | No | Tool metadata and hints |
disabled | bool | No | If true, tool is ignored (default: false) |
description | str | No | Description of what the tool does |
inputSchema | dict[str, Any] | No | JSON Schema defining expected input properties |
execution | HTTPExecutionConfig | CLIExecutionConfig | FileExecutionConfig | TextExecutionConfig | Yes | Execution configuration (determines how tool is executed) |
ExecutionResult
Result format returned from tool execution. Fields:| Field | Type | Required | Description |
|---|---|---|---|
isError | bool | Yes | Whether an error occurred during execution |
content | Any | No | Result content (None if error) |
error | str | No | Error message (None if success) |
metadata | dict[str, Any] | No | Additional metadata (e.g., status_code, execution_time_ms) |
Metadata
Optional metadata about the MCI tool collection. Fields:| Field | Type | Required | Description |
|---|---|---|---|
name | str | No | Name of the tool collection |
description | str | No | Description of the collection |
version | str | No | Version number (e.g., “1.0.0”) |
license | str | No | License type (e.g., “MIT”) |
authors | list[str] | No | List of author names |
Execution Configurations
HTTPExecutionConfig
Configuration for HTTP-based tool execution. Fields:| Field | Type | Required | Default | Description |
|---|---|---|---|---|
type | ExecutionType | Yes | "http" | Execution type identifier |
method | str | No | "GET" | HTTP method (GET, POST, PUT, DELETE, etc.) |
url | str | Yes | - | URL endpoint for the request |
headers | dict[str, str] | No | None | HTTP headers |
auth | AuthConfig | No | None | Authentication configuration |
params | dict[str, Any] | No | None | Query parameters |
body | HTTPBodyConfig | No | None | Request body configuration |
timeout_ms | int | No | 30000 | Request timeout in milliseconds |
retries | RetryConfig | No | None | Retry configuration |
CLIExecutionConfig
Configuration for command-line tool execution. Fields:| Field | Type | Required | Default | Description |
|---|---|---|---|---|
type | ExecutionType | Yes | "cli" | Execution type identifier |
command | str | Yes | - | Command to execute |
args | list[str] | No | None | Command arguments |
flags | dict[str, FlagConfig] | No | None | Command flags configuration |
cwd | str | No | None | Working directory for command execution |
timeout_ms | int | No | 30000 | Execution timeout in milliseconds |
FileExecutionConfig
Configuration for file reading and templating. Fields:| Field | Type | Required | Default | Description |
|---|---|---|---|---|
type | ExecutionType | Yes | "file" | Execution type identifier |
path | str | Yes | - | Path to the file to read |
enableTemplating | bool | No | True | Whether to process template placeholders in file content |
TextExecutionConfig
Configuration for simple text template execution. Fields:| Field | Type | Required | Default | Description |
|---|---|---|---|---|
type | ExecutionType | Yes | "text" | Execution type identifier |
text | str | Yes | - | Text template with placeholder support |
Authentication Models
ApiKeyAuth
API Key authentication configuration. Fields:| Field | Type | Required | Default | Description |
|---|---|---|---|---|
type | str | Yes | "apiKey" | Authentication type |
in | str | Yes | - | Where to place the key: “header” or “query” |
name | str | Yes | - | Name of the header or query parameter |
value | str | Yes | - | API key value (supports templates) |
BearerAuth
Bearer token authentication configuration. Fields:| Field | Type | Required | Default | Description |
|---|---|---|---|---|
type | str | Yes | "bearer" | Authentication type |
token | str | Yes | - | Bearer token value (supports templates) |
BasicAuth
Basic authentication (username/password) configuration. Fields:| Field | Type | Required | Default | Description |
|---|---|---|---|---|
type | str | Yes | "basic" | Authentication type |
username | str | Yes | - | Username (supports templates) |
password | str | Yes | - | Password (supports templates) |
OAuth2Auth
OAuth2 authentication configuration. Fields:| Field | Type | Required | Default | Description |
|---|---|---|---|---|
type | str | Yes | "oauth2" | Authentication type |
flow | str | Yes | - | OAuth2 flow type (e.g., “clientCredentials”) |
tokenUrl | str | Yes | - | Token endpoint URL |
clientId | str | Yes | - | OAuth2 client ID |
clientSecret | str | Yes | - | OAuth2 client secret (supports templates) |
scopes | list[str] | No | None | Optional OAuth2 scopes |
Error Handling
The MCI Python adapter provides consistent error handling across all operations.Exception Types
MCIClientError
Raised byMCIClient methods for client-level errors.
Common Causes:
- Schema file not found or invalid
- Tool not found
- Invalid tool execution
ExecutionResult Error Format
Execution errors are returned asExecutionResult objects with isError=True.
Error Fields:
| Field | Description |
|---|---|
isError | Always True for errors |
content | Always None for errors |
error | Human-readable error message |
metadata | Optional additional error context |
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
-
Schema-level settings (applies to all tools):
-
Tool-level settings (overrides schema-level):
| Scenario | Allowed? |
|---|---|
| File in schema directory | ✓ Yes |
| File in subdirectory of schema directory | ✓ Yes |
| File outside schema directory (no config) | ✗ No - Error |
File in directoryAllowList | ✓ Yes |
Any path with enableAnyPaths: true | ✓ Yes |
- Keep
enableAnyPathsdisabled unless absolutely necessary - Use
directoryAllowListfor specific directories instead ofenableAnyPaths - Validate user input before passing to tools that access files
- Review tool configurations regularly for security implications
Error Handling Best Practices
Check isError Flag: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 (usepropsinstead)
Note:{{input.fieldName}}is supported for backward compatibility but is deprecated. Use{{props.fieldName}}in all new code. Example:
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
TheLiteMcpClient 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:
| Name | Type | Required | Description |
|---|---|---|---|
type | Literal["stdio"] | Yes | Must be “stdio” |
command | str | Yes | Command to run (e.g., “uvx”, “npx”) |
args | List[str] | No | Arguments to pass to the command (default: []) |
env | Dict[str, str] | No | Environment variables for the server process (default: {}) |
SseCfg
Configuration for HTTP/SSE-based MCP servers (web-based servers).
Fields:
| Name | Type | Required | Description |
|---|---|---|---|
type | Literal["http"] | Yes | Must be “http” |
url | HttpUrl | Yes | Server URL (e.g., “http://localhost:8000/mcp”) |
headers | Dict[str, str] | No | HTTP headers for authentication (default: {}) |
ClientCfg
Complete configuration for the LiteMcpClient.
Fields:
| Name | Type | Required | Description |
|---|---|---|---|
server | StdioCfg | SseCfg | Yes | Server connection configuration |
request_timeout | Optional[float] | No | Request timeout in seconds (default: 60.0) |
Initialization
LiteMcpClient(cfg: ClientCfg)
Initialize the LiteMcpClient with configuration.
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
cfg | ClientCfg | Yes | Client configuration specifying server type and connection details |
Usage
TheLiteMcpClient 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
RuntimeError- If session is not initialized (client not used as context manager)
async call_tool(name: str, **arguments: Any) -> Any
Call a tool on the MCP server with the provided arguments.
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
name | str | Yes | Name of the tool to call |
**arguments | Any | No | Keyword arguments to pass to the tool |
Any- The tool execution result from the server (typically containingcontentand metadata)
RuntimeError- If session is not initialized (client not used as context manager)
Complete Examples
STDIO Example (uvx)
STDIO Example (npx)
HTTP Example
Error Handling
RuntimeError: Raised when attempting to use methods outside of context manager:Notes
- The
LiteMcpClientuses the officialmcppackage 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
