Rhesis Services

This module contains the service classes used throughout the Rhesis SDK.

LLM Service

class DocumentExtractor[source]

Bases: Extractor

Extract plain text from supported document files using Markitdown.

supported_extensions: set[str] = {'.csv', '.docx', '.epub', '.htm', '.html', '.json', '.md', '.pdf', '.pptx', '.txt', '.xlsx', '.xml', '.zip'}
__init__()[source]

Initialize the DocumentExtractor.

extract(source)[source]

Extract text from a document source.

Parameters:

source (SourceSpecification) – SourceBase object containing the document source

Return type:

ExtractedSource

Returns:

ExtractedSource object containing the extracted text

Raises:

ValueError – If the source type is not supported

extract_from_bytes(file_content, filename)[source]

Extract text from binary file content using Markitdown.

Parameters:
  • file_content (bytes) – Binary content of the file

  • filename (str) – Original filename with extension

Returns:

Extracted text from the file

Return type:

str

Raises:

ValueError – If the file type is not supported or extraction fails

get_supported_extensions()[source]

Get the list of supported file extensions.

Returns:

Set of supported file extensions (including the dot)

Return type:

set[str]

class MCPAgent(model=None, mcp_client=None, system_prompt=None, max_iterations=10, verbose=False)[source]

Bases: object

Generic MCP Agent for autonomous tool usage with customizable prompts.

Uses a ReAct (Reason-Act-Observe) loop to autonomously call MCP tools and accomplish tasks. Clients can customize behavior via system prompts.

Parameters:
__init__(model=None, mcp_client=None, system_prompt=None, max_iterations=10, verbose=False)[source]

Initialize the MCP agent.

Parameters:
  • model (Union[str, BaseLLM, None], default: None) – Language model for reasoning and decision-making. Can be a string (provider name), BaseLLM instance, or None (uses default).

  • mcp_client (Optional[MCPClient], default: None) – Client connected to an MCP server

  • system_prompt (Optional[str], default: None) – Custom system prompt to define agent behavior (optional)

  • max_iterations (int, default: 10) – Maximum reasoning loops before stopping (default: 10)

  • verbose (bool, default: False) – Print detailed execution logs to stdout (default: False)

async run_async(user_query)[source]

Execute the agent’s ReAct loop asynchronously.

Connects to MCP server, discovers tools, and iteratively reasons about what actions to take until the task is complete or max iterations reached.

Parameters:

user_query (str) – User’s query or task description

Return type:

AgentResult

Returns:

AgentResult with final answer and execution history

run(user_query)[source]

Execute the agent synchronously.

Convenience wrapper around run_async for non-async code.

Parameters:

user_query (str) – User’s query or task description

Return type:

AgentResult

Returns:

AgentResult with final answer and execution history

class MCPClient(server_name, transport_type, transport_params)[source]

Bases: object

Client for connecting to and communicating with MCP servers.

Supports multiple transport types (stdio, HTTP, SSE).

Parameters:
  • server_name (str)

  • transport_type (Literal['stdio', 'http', 'sse'])

  • transport_params (Dict[str, Any])

__init__(server_name, transport_type, transport_params)[source]

Initialize MCP client with transport configuration.

Parameters:
  • server_name (str) – Name for the server (e.g., “notion”)

  • transport_type (Literal['stdio', 'http', 'sse']) – Type of transport (“stdio”, “http”, or “sse”)

  • transport_params (Dict[str, Any]) – Transport-specific parameters: - stdio: {“command”: str, “args”: List[str], “env”: Dict[str, str]} - http: {“url”: str, “headers”: Dict[str, str]} - sse: {“url”: str, “headers”: Dict[str, str]}

async connect()[source]

Connect to MCP server using the configured transport.

Routes to transport-specific connection method based on transport type. Must be called before any other operations.

Return type:

None

async disconnect()[source]

Disconnect from the MCP server.

Return type:

None

async list_resources()[source]

List all available resources from the MCP server.

Return type:

List[Dict[str, Any]]

Returns:

List of resource dictionaries with uri, name, description, etc.

async read_resource(uri)[source]

Read content from a specific resource.

Parameters:

uri (str) – The URI of the resource to read

Return type:

str

Returns:

The text content of the resource

async call_tool(tool_name, arguments=None)[source]

Call a tool provided by the MCP server.

Parameters:
  • tool_name (str) – Name of the tool to call

  • arguments (Optional[Dict[str, Any]], default: None) – Optional arguments for the tool

Return type:

Any

Returns:

The result of the tool call

async list_tools()[source]

List all tools exposed by this MCP server.

Return type:

List[Dict[str, Any]]

Returns:

List of dicts with ‘name’, ‘description’, and ‘inputSchema’ fields

class MCPClientFactory(config_path=None, config_dict=None)[source]

Bases: object

Factory for creating MCP clients from configuration.

Loads and parses MCP server configurations from files, dicts, or templates, detects transport types, and creates pre-configured MCPClient instances.

Parameters:
__init__(config_path=None, config_dict=None)[source]

Initialize client factory with config file path or config dict.

Parameters:
  • config_path (Optional[str], default: None) – pathlib.Path to mcp.json config file. Required if config_dict is not provided.

  • config_dict (Optional[Dict], default: None) – Direct configuration dictionary in MCP format: {“mcpServers”: {“serverName”: {…}}} Required if config_path is not provided.

Raises:

ValueError – If neither config_path nor config_dict is provided.

create_client(server_name)[source]

Create an MCP client from configuration.

Loads config, detects transport type, and creates a pre-configured MCPClient instance.

Parameters:

server_name (str) – Name of the MCP server from the config

Return type:

MCPClient

Returns:

Configured MCPClient instance ready to connect

Raises:
classmethod from_tool_config(tool_config, credentials)[source]

Create MCPClientFactory from MCP configuration with credential substitution.

Parameters:
  • tool_config (Dict) – Full MCP config with credential placeholders: {“mcpServers”: {“name”: {…}}}

  • credentials (Dict[str, str]) – Dictionary of credential key-value pairs to substitute

Returns:

MCPClientFactory instance configured with the tool

Example

tool_config = {
“mcpServers”: {
“notion”: {

“transport”: “stdio”, “command”: “npx”, “args”: [“-y”, “@notionhq/notion-mcp-server”], “env”: {“NOTION_TOKEN”: “{{ NOTION_TOKEN }}”}

}

}

} credentials = {“NOTION_TOKEN”: “ntn_abc123…”} factory = MCPClientFactory.from_tool_config(tool_config, credentials)

classmethod from_provider(provider, credentials)[source]

Create MCPClientFactory from a built-in provider template.

Loads the provider’s template file and renders it with credentials.

Parameters:
  • provider (str) – Provider name (e.g., “notion”, “github”, “jira”)

  • credentials (Dict[str, str]) – Dictionary of credential key-value pairs

Returns:

MCPClientFactory instance ready to use

Example

factory = MCPClientFactory.from_provider(

“notion”, {“NOTION_TOKEN”: “ntn_abc123…”}

)

class ToolExecutor(mcp_client)[source]

Bases: object

Handles execution of MCP tool calls.

Separates pure tool execution from agent logic.

Parameters:

mcp_client (MCPClient)

__init__(mcp_client)[source]

Initialize the executor.

Parameters:

mcp_client (MCPClient) – Connected MCP client for calling tools

async get_available_tools()[source]

Get list of available tools from the MCP server.

Return type:

List[Dict[str, Any]]

Returns:

List of tool dictionaries with name, description, and input schema

async execute_tool(tool_call)[source]

Execute a tool and return its result.

Parameters:

tool_call (ToolCall) – Specifies which tool to call and with what arguments

Return type:

ToolResult

Returns:

ToolResult with success=True/False based on application layer outcome

Raises:
  • MCPConnectionError – If connection to MCP server fails (infrastructure layer)

  • MCPApplicationError – If tool returns fatal error (5xx, 401, 403) - 404 and other 4xx errors are treated as recoverable