MCP-Compliant LLM Integration Framework
Project description
Agentical: MCP-Compliant LLM Integration Framework
A robust Python framework for integrating Large Language Models (LLMs) with tools using the Model Context Protocol (MCP). This implementation provides a clean, type-safe, and maintainable way to connect LLMs with external tools and data sources.
Table of Contents
- Features
- Quick Start
- Multiple MCP Server Usage
- API Documentation
- Architecture
- Environment Variables
- Logging System
- Troubleshooting
- Development
- Contributing
- License
- Acknowledgments
Features
- ๐ MCP Protocol Integration
- ๐ Async/Await First Design
- ๐ ๏ธ Modular LLM Backend Support (OpenAI, Gemini)
- ๐ฏ Type-Safe Tool Integration
- ๐ Comprehensive Error Handling
- ๐งน Automatic Resource Management with AsyncExitStack
- ๐ Robust Configuration Validation
- ๐ฎ Interactive Server Selection
- ๐ฆ Clean Separation of Concerns
Quick Start
Installation
# Create and activate virtual environment
python -m venv .venv
source .venv/bin/activate # Linux/Mac
# or
.venv\Scripts\activate # Windows
# Install from PyPI
pip install beanone-agentical
Running the Example
-
Download everything under the server folder to your local server folder
-
Create a
.envfile with your API keys:# .env file OPENAI_API_KEY=your_openai_key # If using OpenAI backend # or GEMINI_API_KEY=your_gemini_key # If using Gemini backend
-
Create
config.jsonfrom theconfig_template.json:cp config_template.json config.json # Then edit config.json with your settings
-
Download one of the demo files (e.g.,
demo_openai.py) -
Run the demo:
# Run with OpenAI backend python demo_openai.py # Or with custom configuration python demo_openai.py -c custom_config.json
-
When prompted, you can:
- Select a specific MCP server to use its tools
- Choose "Connect to all servers" to let the LLM use tools from any available server
-
Example queries using multiple tools:
Here are some example queries that demonstrate the power of combining multiple servers:
Weather Comparison Across Cities:
Use the calculator-server to find the temperature difference between Seattle and Beijing in celsius
This query uses the weather server to:
- Get current weather in Seattle
- Get current weather in Beijing
- Calculate and display the temperature difference
Note: Calculator-server is specified because LLMs typically do the math themselves but we want to demo the multi-tool use example.
Research and Local Storage:
Search for Python async best practices and save them to a local markdown file
This query combines:
- Brave Search server for research
- File system server for saving results
API Documentation
Comprehensive API documentation is available in the docs/api directory:
- API Overview: Complete overview of the API structure and components
- Core Components: Detailed documentation of core interfaces and classes
- Configuration: Configuration options and providers
- Tool Integration: Guide for integrating and implementing tools
- Error Handling: Error handling strategies and best practices
- Examples: Practical examples and usage patterns
The API includes three sample LLM backend implementations (OpenAI, Anthropic, and Gemini) that demonstrate how to integrate with different LLM providers. While these implementations have complete code coverage and serve as reference implementations, they are provided as examples only. Users should thoroughly evaluate and test these implementations before using them in production environments.
Architecture
The framework follows a clean, layered architecture:
โโโโโโโโโโโโโโโโโโโ agentical/
โ API Layer โ โโโ api/ # Core abstractions & interfaces
โ โ โ โโโ llm_backend.py # LLM abstraction layer
โโโโโโโโโโโโโโโโโโโค โ
โ MCP Integration โ โโโ mcp/ # MCP protocol integration
โ โ โ โโโ provider.py # Tool provider implementation
โโโโโโโโโโโโโโโโโโโค โ
โ Client โ โโโ chat_client.py # Generic LLM client implementation
โ Implementation โ โ
โ โ โโโ llm/ # LLM implementations
โ โ โ โโโ anthropic/ # Anthropic implementation
โ โ โ โโโ gemini/ # Gemini implementation
โ โ โ โโโ openai/ # OpenAI implementation
โโโโโโโโโโโโโโโโโโโ
For detailed information about specific components:
- Provider Architecture: Detailed overview of the provider implementation
- System Lifecycles: Comprehensive documentation of system state transitions and lifecycles
Here is a more detailed view of the system architecture and component relationships:
graph TD
subgraph Application_Layer["USER APPLICATION LAYER"]
App[Your Application]
Chat[Chat Client]
App --> Chat
note1[Choose how to integrate:<br/>1. Use Chat Client<br/>2. Use Provider directly]
note1 -.-> App
end
subgraph Integration_Layer
Provider[MCPToolProvider]
Chat --> Provider
end
subgraph MCP_Layer
MCP[MCPClient]
Session[MCPSession]
Config[MCPConfig]
MCP --> Session
MCP --> Config
Provider --> MCP
end
subgraph LLM_Layer[LLM Layer - Choose Your Provider]
LLMBackend["LLMBackend (Interface)"]
Adapter[SchemaAdapter]
Gemini[GeminiBackend]
OpenAI[OpenAIBackend]
Anthropic[AnthropicBackend]
LLMBackend --> Gemini
LLMBackend --> OpenAI
LLMBackend --> Anthropic
Adapter -.- Anthropic
Provider --> LLMBackend
note2[Different LLM implementations:<br/>- OpenAI GPT<br/>- Google Gemini<br/>- Anthropic Claude]
note2 -.-> LLMBackend
end
subgraph Tool_Layer[Tool Layer - Add MCP Servers]
Tools[MCP Tools]
Session --> Tools
GlamaLink["glama.ai/mcp/servers"]
SmitheryLink["smithery.ai"]
CustomTools["server/ (local implementations)"]
note3[Implement your own MCP Servers<br/>or use from public repos]
note3 -.-> GlamaLink
note3 -.-> SmitheryLink
note3 -.-> CustomTools
GlamaLink --> Tools
SmitheryLink --> Tools
CustomTools --> Tools
end
classDef default fill:#1a1a1a,stroke:#333,stroke-width:2px,color:#fff;
classDef focus fill:#4a148c,stroke:#4a148c,stroke-width:2px,color:#fff;
classDef active fill:#1b5e20,stroke:#1b5e20,stroke-width:2px,color:#fff;
classDef note fill:#ffd6d6,stroke:#662222,stroke-width:2px,color:#662222;
classDef link fill:#1a1a1a,stroke:#0288d1,stroke-width:3px,color:#29b6f6,font-weight:bold;
class App,Chat,MCP,Session,Config,Adapter,Gemini,OpenAI,Anthropic,Tools default;
class Provider,LLMBackend focus;
class note1,note2,note3 note;
class Application_Layer active;
class GlamaLink,SmitheryLink,CustomTools link;
click GlamaLink "https://glama.ai/mcp/servers" _blank
click SmitheryLink "https://smithery.ai" _blank
click CustomTools "https://github.com/beanone/agentical/tree/main/server" _blank
Key Components
-
MCPToolProvider: MCP interactions (Provider Architecture and System Lifecycles for more detail)
- Load MCP servers from configuration (Discovery based can be implemented later)
- Handles server connection and lifecycle management
- Manages resource lifecycle with AsyncExitStack
- Provides clean error handling and validation
- Implements comprehensive component lifecycles and state management
-
LLMBackend: Abstract interface for LLM implementations
- Type-safe tool integration
- Async query processing
- Pluggable provider support
-
chat_client: A Facade that encapsulates the integration of LLM with MCPToolProvider
- Async tool execution
- Resource cleanup guarantees
- Error handling
MCP Integration
- Quickly implement your own
- Implement a MCP server: see examples under server
- Add the server configuration to your
config.json - See config_template.json for how to configure
- Follow links GlamaLink or SmitheryLink
- Add the server configuration to your
config.json - Set any required environment variables (such as related API key in .env)
- Add the server configuration to your
Each server in the configuration must implement the Model Context Protocol. The configuration specifies:
command: The command to launch the MCP serverargs: Arguments passed to the server commandenv: Optional environment variables for the serverworking_dir: Optional working directory for the server
Environment Variables
Set in a .env file:
# API Keys (Required for respective backends)
OPENAI_API_KEY=your_openai_key # Required for OpenAI backend
# Model Selection (Optional - will use defaults if not set)
OPENAI_MODEL=gpt-4-turbo-preview # Default model for OpenAI
# Server Configuration (Set based on your MCP servers)
OPENWEATHERMAP_API_KEY=your_weather_key # Required for weather server
WORKSPACE_DIR=/path/to/workspace # Optional for file operations
Each LLM backend has its own environment variables for API keys and model selection:
-
OpenAI Backend
OPENAI_API_KEY: Required for authenticationOPENAI_MODEL: Optional, defaults to "gpt-4-turbo-preview"
-
Anthropic Backend
ANTHROPIC_API_KEY: Required for authenticationANTHROPIC_MODEL: Optional, defaults to "claude-3-opus-20240229"
-
Gemini Backend
GEMINI_API_KEY: Required for authenticationGEMINI_MODEL: Optional, defaults to "gemini-2.0-flash-001"
-
server-specific variables
- such as OPENWEATHERMAP_API_KEY if you use a weather server.
Logging System
The framework includes a comprehensive logging system with:
- Structured logging with timestamps and log levels
- Optional rotating log files
- Log message sanitization
- Configurable log levels
For detailed configuration, see Logging Configuration.
Troubleshooting
Common issues and solutions:
-
API Key Configuration
- Ensure environment variables are set correctly in
.env - Check
.envfile format and permissions - Verify API keys are valid and have sufficient permissions
- Ensure environment variables are set correctly in
-
Server Connection
- Verify server configurations in
config.json - Check network connectivity to MCP servers
- Ensure required ports are available
- Check server logs for connection errors
- Verify server configurations in
-
Tool Execution
- Verify tool permissions and access rights
- Check resource availability (memory, disk space)
- Review tool-specific error messages
- Check server health status
-
Configuration Issues
- Validate
config.jsonagainstconfig_template.json - Check for missing or invalid configuration values
- Verify environment variables are properly set
- Ensure working directories exist and are accessible
- Validate
For more detailed troubleshooting, see the Error Handling documentation.
Development
Prerequisites
- Python 3.12+ (Lower versions may work but are not officially tested)
Setup Development Environment
# Clone repository
git clone <repository-url>
cd agentical
# Create and activate virtual environment
python -m venv .venv
source .venv/bin/activate
# Install package in development mode
pip install -e .
# Install development dependencies
pip install -r requirements-dev.txt
Implementing New LLM Backends
- Inherit from
LLMBackendabstract base class - Implement required methods:
process_query: Handle query processing and tool executionconvert_tools: Convert MCP tools to LLM-specific format
- Add proper error handling and resource management
- Follow existing patterns in OpenAI/Gemini implementations
Contributing
- Fork the repository
- Create a feature branch
- Implement changes with tests
- Ensure all tests pass
- Create a Pull Request
License
Acknowledgments
- Built on the Model Context Protocol
- Uses the official MCP Python SDK
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file beanone_agentical-0.3.0.tar.gz.
File metadata
- Download URL: beanone_agentical-0.3.0.tar.gz
- Upload date:
- Size: 97.1 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.12.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
9a7c9495a6eb74818365de1e68560e2387be51077c22a90893514a215ae1a3f4
|
|
| MD5 |
8c857eff949e0c264a78711da83f8765
|
|
| BLAKE2b-256 |
6d1461e1e8dbe43b657d54074120ef84d912e490b254a7755b2732bf2c5b9aa3
|
File details
Details for the file beanone_agentical-0.3.0-py3-none-any.whl.
File metadata
- Download URL: beanone_agentical-0.3.0-py3-none-any.whl
- Upload date:
- Size: 46.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.12.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
a7a7f56ac6c078a43d238672092b0d0c5c0116c077d7c69765d64f12003e582b
|
|
| MD5 |
111338bf27242c56f393e76b0fa2f44b
|
|
| BLAKE2b-256 |
079020d3a9c79ea84fa1c49a2f30ef155d7307b19621112aae7dcd9942969e32
|