Klever MCP Server
OfficialClick on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@Klever MCP Server show me best practices for Klever token contracts"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
Klever MCP Server
A Model Context Protocol (MCP) server tailored for Klever blockchain smart contract development. This server maintains and serves contextual knowledge including code patterns, best practices, and runtime behavior for developers working with the Klever VM SDK.
Features
š Triple Mode Operation: Run as HTTP API server, MCP stdio server, or public hosted MCP server
š¾ Flexible Storage: In-memory or Redis backend support
š Smart Context Retrieval: Query by type, tags, or contract type
š Automatic Pattern Extraction: Parse Klever contracts to extract examples and patterns
šÆ Relevance Ranking: Intelligent scoring and ranking of context
š Live Updates: Add and update context in real-time
š”ļø Type Safety: Full TypeScript with Zod validation
š Comprehensive Knowledge Base: Pre-loaded with Klever VM patterns, best practices, and examples
š§ Contract Validation: Automatic detection of common issues and anti-patterns
š Deployment Scripts: Ready-to-use scripts for contract deployment, upgrade, and querying
Related MCP server: code-graph-rag-mcp
Quick Start
Install and run instantly via npx ā no cloning required:
npx -y @klever/mcp-serverOr connect to the hosted public server:
claude mcp add -t http klever-vm https://mcp.klever.org/mcpSee MCP Client Integration for client-specific configuration.
Architecture
mcp-klever-vm/
āāā src/
ā āāā api/ # HTTP API routes with validation
ā āāā context/ # Context management service layer
ā āāā mcp/ # MCP protocol server implementation
ā āāā parsers/ # Klever contract parser and validator
ā āāā storage/ # Storage backends (memory/Redis)
ā ā āāā memory.ts # In-memory storage with size limits
ā ā āāā redis.ts # Redis storage with optimized queries
ā āāā types/ # TypeScript type definitions
ā āāā utils/ # Utilities and ingestion tools
ā āāā knowledge/ # Modular knowledge base (95+ entries)
ā āāā core/ # Core concepts and imports
ā āāā storage/ # Storage patterns and mappers
ā āāā events/ # Event handling and rules
ā āāā tokens/ # Token operations and decimals
ā āāā modules/ # Built-in modules (admin, pause)
ā āāā tools/ # CLI tools (koperator, ksc)
ā āāā scripts/ # Helper scripts
ā āāā examples/ # Complete contract examples
ā āāā errors/ # Error patterns
ā āāā best-practices/ # Optimization and validation
ā āāā documentation/ # API reference
āāā tests/ # Test files
āāā docs/ # DocumentationKey Improvements Made
Storage Layer
Added memory limits to prevent OOM in InMemoryStorage
Optimized Redis queries to avoid O(N) KEYS command
Added atomic transactions for Redis operations
Improved error handling and validation
API Security
Added input validation for all endpoints
Batch operation size limits
Proper error responses without leaking internals
Environment-aware error messages
Type Safety
Centralized schema validation
Proper TypeScript interfaces for options
Runtime validation of stored data
Performance
Batch operations using Redis MGET
Index-based queries instead of full scans
Optimized count operations
Installation
Clone the repository:
git clone https://github.com/klever-io/mcp-klever-vm.git
cd mcp-klever-vmInstall dependencies:
pnpm installCopy environment configuration:
cp .env.example .envInstall Klever SDK tools (required for transactions):
chmod +x scripts/install-sdk.sh && ./scripts/install-sdk.shBuild the project:
pnpm run buildConfiguration
Edit .env file to configure the server:
# Server Mode (http, mcp, or public)
MODE=http
# HTTP Server Port (only for http mode)
PORT=3000
# Storage Backend (memory or redis)
STORAGE_TYPE=memory
# Maximum contexts for in-memory storage (default: 10000)
MEMORY_MAX_SIZE=10000
# Redis URL (only if STORAGE_TYPE=redis)
REDIS_URL=redis://localhost:6379
# Node environment (development or production)
NODE_ENV=developmentMCP Client Integration
Claude Code
# Add via npx (recommended)
claude mcp add klever-vm -- npx -y @klever/mcp-server
# Or connect to the public hosted server
claude mcp add -t http klever-vm https://mcp.klever.org/mcpClaude Desktop
Add to your claude_desktop_config.json:
{
"mcpServers": {
"klever-vm": {
"command": "npx",
"args": ["-y", "@klever/mcp-server"]
}
}
}For detailed setup, see the Claude Desktop Installation Guide.
Cursor
Add to your Cursor MCP settings (.cursor/mcp.json):
{
"mcpServers": {
"klever-vm": {
"command": "npx",
"args": ["-y", "@klever/mcp-server"]
}
}
}VS Code (GitHub Copilot)
Add to .vscode/mcp.json in your project:
{
"servers": {
"klever-vm": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@klever/mcp-server"]
}
}
}For detailed setup, see the VS Code Installation Guide.
Public MCP Server
The Klever MCP Server can be hosted as a public shared service, allowing any developer to connect without running it locally.
Connecting to the Public Server
# Add permanently (user-level)
claude mcp add -t http klever-vm https://mcp.klever.org/mcp
# Add for current project only
claude mcp add -t http -s project klever-vm https://mcp.klever.org/mcpAvailable Tools (Public Mode)
The public server exposes a read-only subset of tools for security:
Tool | Description |
| Search the Klever VM knowledge base |
| Retrieve a specific context by ID |
| Find contexts similar to a given context |
| Get knowledge base statistics |
| Enhance queries with relevant Klever VM context |
Write operations (add_context) and shell-based tools (init_klever_project, add_helper_scripts) are disabled in public mode.
Self-Hosting with Docker
# Build and run
docker build -t mcp-klever-vm .
docker run -p 3000:3000 mcp-klever-vm
# Or using docker compose
docker compose up -dThen connect:
claude mcp add -t http klever-vm-local http://localhost:3000/mcpSelf-Hosting without Docker
pnpm install
pnpm run build
pnpm run start:publicEnvironment Variables (Public Mode)
Variable | Default | Description |
|
| Set to |
|
| Server port |
| (unset) | Comma-separated allowed origins. Unset or |
|
| MCP endpoint requests/min per IP |
|
| API endpoint requests/min per IP |
|
| Max request body size |
Deployment Notes
For production at mcp.klever.org:
Deploy Docker container behind a reverse proxy (nginx/Caddy/cloud LB) for TLS termination
Ensure proxy passes
mcp-session-idheader and supports SSE (disable response buffering)Single instance is sufficient as the server is read-only with an in-memory knowledge base
Consider Cloudflare for DDoS protection (SSE is supported)
Usage
Knowledge Base Loading
The server automatically loads the Klever knowledge base based on your storage type:
Memory Storage (Default)
Knowledge is automatically loaded when the server starts
No need to run
pnpm run ingestseparatelyData exists only while server is running
Best for development and testing
Redis Storage
# First, ingest the knowledge base (one time)
pnpm run ingest
# Then start the server
pnpm run devKnowledge persists in Redis database
Survives server restarts
Best for production use
This will load:
Smart contract templates and examples
Annotation rules and best practices
Storage mapper patterns and comparisons
Deployment and query scripts
Common errors and solutions
Testing patterns
API reference documentation
Running as HTTP Server
# Development mode
pnpm run dev
# Production mode
pnpm run build && pnpm startThe HTTP API will be available at http://localhost:3000/api
Running as MCP Server
MODE=mcp pnpm startUse with any MCP-compatible client.
API Endpoints
POST /api/context
Ingest new context into the system.
{
"type": "code_example",
"content": "contract code here",
"metadata": {
"title": "Token Contract Example",
"description": "ERC20-like token implementation",
"tags": ["token", "fungible"],
"contractType": "token"
}
}GET /api/context/:id
Retrieve specific context by ID.
POST /api/context/query
Query contexts with filters.
{
"query": "transfer",
"types": ["code_example", "best_practice"],
"tags": ["token"],
"contractType": "token",
"limit": 10,
"offset": 0
}PUT /api/context/:id
Update existing context.
DELETE /api/context/:id
Delete context.
GET /api/context/:id/similar
Find similar contexts.
POST /api/context/batch
Batch ingest multiple contexts.
MCP Tools
When running as MCP server, the following tools are available:
query_context: Search for relevant Klever development contextadd_context: Add new context to the knowledge baseget_context: Retrieve specific context by IDfind_similar: Find contexts similar to a given contextget_knowledge_stats: Get statistics about the knowledge baseinit_klever_project: Initialize a new Klever smart contract project with helper scriptsenhance_with_context: Automatically enhance queries with relevant Klever VM context
Context Types
code_example: Working code snippets and examples (Rust smart contract code)best_practice: Recommended patterns and practicessecurity_tip: Security considerations and warningsoptimization: Performance optimization techniquesdocumentation: General documentation and guideserror_pattern: Common errors and solutionsdeployment_tool: Deployment scripts and utilities (bash scripts, tools)runtime_behavior: Runtime behavior explanations
Pre-loaded Knowledge Base
The MCP server includes a comprehensive knowledge base with 95+ entries organized into 11 categories:
Critical Patterns
Payment handling and token operations
Decimal conversions and calculations
Event emission and parameter rules
CLI tool usage and best practices
Contract Patterns & Examples
Basic contract structure templates
Complete lottery game implementation
Staking contract with rewards
Cross-contract communication patterns
Remote storage access patterns
Token mapper helper modules
Development Tools
Koperator: Complete CLI reference with argument encoding
KSC: Build commands and project setup
Deployment, upgrade, and query scripts
Interactive contract management tools
Common utilities library (bech32, network management)
Storage & Optimization
Storage mapper selection guide with performance comparisons
Namespace organization patterns
View endpoints for efficient queries
Gas optimization techniques
OptionalValue vs Option patterns
Best Practices & Security
Input validation patterns
Error handling strategies
Admin and pause module usage
Access control patterns
Common mistakes and solutions
Ingesting Contracts
Use the built-in ingestion utilities to parse and import Klever contracts:
import { StorageFactory } from './storage/index.js';
import { ContextService } from './context/service.js';
import { ContractIngester } from './utils/ingest.js';
const storage = StorageFactory.create('memory');
const contextService = new ContextService(storage);
const ingester = new ContractIngester(contextService);
// Ingest a single contract
await ingester.ingestContract('./path/to/contract.rs', 'AuthorName');
// Ingest entire directory
await ingester.ingestDirectory('./contracts', 'AuthorName');
// Add common patterns
await ingester.ingestCommonPatterns();Development
# Run tests
pnpm test
# Lint code
pnpm run lint
# Format code
pnpm run format
# Watch mode
pnpm run dev
# Ingest/update knowledge base
pnpm run ingestContract Validation
The server can automatically validate Klever contracts and detect issues:
import { KleverValidator } from './parsers/validators.js';
const issues = KleverValidator.validateContract(contractCode);
// Returns array of detected issues with suggestionsValidation checks include:
Event annotation format (double quotes, camelCase)
Managed type API parameters
Zero address validation in transfers
Optimal storage mapper selection
Module naming conventions
Example Use Cases
1. Smart Contract Development Assistant
Integrate with your IDE to provide context-aware suggestions for Klever contract development.
2. Code Review Tool
Automatically check contracts against best practices and security patterns.
3. Learning Platform
Provide examples and explanations for developers learning Klever development.
4. Documentation Generator
Extract and organize contract documentation automatically.
Project Specifications and Examples
For complete project implementation examples and specifications, see:
Project Specification Template - A fill-in template for specifying Klever smart contract projects. Guides AI assistants through MCP knowledge discovery, task tracking, and phased implementation. Includes a KleverDice example.
Project Initialization
The MCP server includes a powerful project initialization tool that creates a new Klever smart contract project with all necessary helper scripts.
Using the init_klever_project Tool
When connected via MCP, use the init_klever_project tool:
{
"name": "my-token-contract",
"template": "empty",
"noMove": false
}Parameters:
name(required): The name of your contracttemplate(optional): Template to use (default: "empty")noMove(optional): If true, keeps project in subdirectory (default: false)
Generated Helper Scripts
The tool creates the following scripts in the scripts/ directory:
build.sh: Builds the smart contract
deploy.sh: Deploys to Klever testnet with auto-detection of contract artifacts
upgrade.sh: Upgrades existing contract (auto-detects from history.json)
query.sh: Query contract endpoints with proper encoding/decoding
test.sh: Run contract tests
interact.sh: Shows usage examples and available commands
Example Workflow
Initialize project:
# Via MCP tool init_klever_project({"name": "my-contract"})Build contract:
./scripts/build.shDeploy to testnet:
./scripts/deploy.shQuery contract:
./scripts/query.sh --endpoint getSum ./scripts/query.sh --endpoint getValue --arg myKeyUpgrade contract:
./scripts/upgrade.sh
All deployment history is tracked in output/history.json for easy reference.
Automatic Context Enhancement
The MCP server can automatically enhance queries with relevant Klever VM context. This ensures your MCP client always has access to the most relevant information.
Using Context Enhancement
Use the enhance_with_context tool to automatically add relevant context to any query:
{
"tool": "enhance_with_context",
"arguments": {
"query": "How do I create a storage mapper?",
"autoInclude": true
}
}This will:
Extract relevant keywords from the query
Search the knowledge base for matching contexts
Return an enhanced query with context included
Provide metadata about what was found
Integration Pattern
For MCP clients that want to always check Klever context first:
// Always enhance Klever-related queries
if (query.match(/klever|kvm|smart contract|endpoint/i)) {
const enhanced = await callTool('enhance_with_context', { query });
// Use enhanced.enhancedQuery for processing
}The context enhancement feature automatically enriches queries with relevant Klever VM knowledge from the comprehensive knowledge base.
Integration Examples
VS Code Extension
// Query for token transfer examples
const response = await fetch('http://localhost:3000/api/context/query', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
query: 'transfer',
types: ['code_example'],
contractType: 'token'
})
});CLI Tool
# Using curl to add context
curl -X POST http://localhost:3000/api/context \
-H "Content-Type: application/json" \
-d '{
"type": "security_tip",
"content": "Always check for zero address",
"metadata": {
"title": "Zero Address Check",
"tags": ["security", "validation"]
}
}'Contributing
Contributions are welcome! Please:
Fork the repository
Create a feature branch
Make your changes
Add tests
Submit a pull request
License
MIT License - see LICENSE file for details
Acknowledgments
Inspired by Context7 by Upstash
Built for the Klever Blockchain
Uses the Klever VM SDK (Rust)
Available Tools
23 toolsadd_contextAInspect
Add a new knowledge entry to the Klever VM context store. Use this to save code examples, best practices, security tips, or documentation that can later be retrieved via query_context or search_documentation. Returns the generated ID of the new entry.
Inputs: type (required), content (required), metadata (required).
add_helper_scriptsAIdempotentInspect
Add build, deploy, upgrade, query, test, and interact automation scripts to an existing Klever smart contract project. Creates a scripts/ directory with bash scripts and updates .gitignore. Run this from the project root directory (where Cargo.toml is located). This tool generates scaffold files ā for koperator CLI syntax reference (correct flags like --args, --values for payments), use search_documentation instead.
Inputs: contractName.
analyze_contractARead-onlyIdempotentInspect
Analyze Klever smart contract Rust source code for common issues. Checks for missing imports, missing #[klever_sc::contract] macro, missing endpoint annotations, payable handlers without call_value usage, storage mappers without #[storage_mapper], and missing event definitions. Returns findings with severity (error/warning/info) and links to relevant knowledge base entries.
Inputs: sourceCode (required), contractName.
check_sdk_statusARead-onlyIdempotentInspect
Check whether the Klever SDK is installed and report the status of each component. Returns JSON with installation state and versions for: ksc (smart contract compiler), koperator (blockchain CLI), VM library (libvmexeccapi), and wallet key file. Run this before init_klever_project or install_klever_sdk to verify prerequisites.
Inputs: no named parameters.
deploy_scAInspect
Build an unsigned smart contract deployment transaction for the Klever blockchain. Provide either wasmPath (preferred ā reads the file server-side) or wasmHex. Returns the unsigned transaction for client-side signing. The MCP server NEVER handles private keys.
Inputs: sender (required), wasmPath, wasmHex, initArgs, +1 more.
enhance_with_contextARead-onlyIdempotentInspect
Augment a natural-language query with relevant Klever VM knowledge base context. Extracts Klever-specific keywords, finds matching entries, and returns the original query combined with relevant code examples and documentation in markdown. Use this to enrich a user prompt before answering Klever development questions.
Inputs: query (required), autoInclude.
find_similarARead-onlyIdempotentInspect
Find knowledge base entries similar to a given entry by comparing tags and content. Returns related contexts ranked by similarity score. Useful for discovering related patterns, examples, or documentation after finding one relevant entry.
Inputs: id (required), limit.
freeze_klvAInspect
Build an unsigned Freeze KLV transaction on the Klever blockchain. Freezing KLV provides energy/bandwidth for network operations and enables staking rewards. Returns the unsigned transaction for client-side signing.
Inputs: sender (required), amount (required), network.
get_accountARead-onlyIdempotentInspect
Get full account details for a Klever blockchain address including nonce, balance, frozen balance, allowance, and permissions. Use this when you need comprehensive account state beyond just the balance.
Inputs: address (required), network.
get_asset_infoARead-onlyIdempotentInspect
Get complete properties and configuration for any asset on the Klever blockchain (KLV, KFI, KDA tokens, NFT collections). Returns supply info, permissions (CanMint, CanBurn, etc.), roles, precision, and metadata. Note: string fields like ID, Name, Ticker are base64-encoded in the raw response.
Inputs: assetId (required), network.
get_balanceARead-onlyIdempotentInspect
Get the KLV or KDA token balance for a Klever blockchain address. Returns the balance in the smallest unit (for KLV: 1 KLV = 1,000,000 units with 6 decimal places). Optionally specify an asset ID to query a specific KDA token balance instead of KLV.
Inputs: address (required), assetId, network.
get_blockARead-onlyIdempotentInspect
Get block information from the Klever blockchain by nonce (block number). If no nonce is provided, returns the latest block. Returns hash, timestamp, proposer, number of transactions, and other block metadata.
Inputs: nonce, network.
get_contextARead-onlyIdempotentInspect
Retrieve a single knowledge base entry by its unique ID. Returns the full entry including content, metadata, tags, and related context IDs. Use this after query_context or find_similar to get complete details for a specific entry.
Inputs: id (required).
get_knowledge_statsARead-onlyIdempotentInspect
Get summary statistics of the Klever VM knowledge base. Returns total entry count, counts broken down by context type (code_example, best_practice, security_tip, etc.), and a sample entry title for each type. Useful for understanding what knowledge is available before querying.
Inputs: no named parameters.
get_transactionARead-onlyIdempotentInspect
Get transaction details by hash from the Klever blockchain. Returns sender, receiver, status, block info, contracts, and receipts. Uses the API proxy for indexed data.
Inputs: hash (required), network.
init_klever_projectAInspect
Scaffold a new Klever smart contract project using the SDK. Creates the Rust project structure via ksc new and generates automation scripts (build, deploy, upgrade, query, test, interact). Requires Klever SDK installed at ~/klever-sdk/. Run check_sdk_status first to verify.
Inputs: name (required), template, noMove.
install_klever_sdkAIdempotentInspect
Download and install Klever SDK tools to ~/klever-sdk/. Fetches the latest versions from the Klever CDN, installs binaries, and downloads required VM library dependencies. Supports macOS (arm64/amd64) and Linux. Run check_sdk_status first to see what is already installed.
Inputs: tool.
invoke_scAInspect
Build an unsigned smart contract invocation transaction on the Klever blockchain. Calls a state-changing endpoint on a deployed contract. Returns the unsigned transaction for client-side signing. For read-only calls, use query_sc instead.
Inputs: sender (required), scAddress (required), funcName (required), args, +2 more.
list_validatorsARead-onlyIdempotentInspect
List active validators on the Klever blockchain network. Returns validator addresses, names, commission rates, delegation info, and staking amounts.
Inputs: network.
query_contextARead-onlyIdempotentInspect
Search the Klever VM knowledge base for smart contract development context. Returns structured JSON with matching entries, scores, and pagination. Use this for precise filtering by type or tags; use search_documentation for human-readable "how do I..." answers.
Inputs: query, types, tags, contractType, +2 more.
query_scARead-onlyIdempotentInspect
Execute a read-only query against a Klever smart contract (VM view call). Returns the contract function result as base64-encoded return data. Arguments must be base64-encoded. Use this to read contract state without modifying it.
Inputs: scAddress (required), funcName (required), args, caller, +1 more.
search_documentationARead-onlyIdempotentInspect
Search Klever VM documentation and knowledge base. Returns human-readable markdown with titles, descriptions, and code snippets. Covers koperator CLI syntax (sc invoke, sc create, sc upgrade), --args type prefixes, --values payment flags, contract metadata flags, ABI decoding, and all smart contract development topics. ALWAYS use this tool first when you need to know the correct flags or argument syntax for koperator commands. Use this instead of query_context when you need formatted developer documentation.
Inputs: query (required), category.
send_transferAInspect
Build an unsigned KLV or KDA token transfer transaction on the Klever blockchain. Returns the unsigned transaction data and hash for client-side signing. The MCP server NEVER handles private keys ā signing must be done externally.
Inputs: sender (required), receiver (required), amount (required), assetId, +1 more.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelogā¦
TDQS
Scored across 23 tools
Tools have clearly distinct purposes. For example, query_context and search_documentation both search the knowledge base but differ in output format (structured JSON vs human-readable markdown). All other tools target different resources or actions.
All tool names follow a consistent verb_noun pattern with underscores, such as add_context, get_balance, deploy_sc. No mixing of conventions.
23 tools is on the higher end of the acceptable range. The server covers a broad domain including blockchain queries, smart contract lifecycle, and knowledge management, so the count is justified but some consolidation (e.g., reducing knowledge base tools) could improve coherence.
The tool set covers major workflows: SDK installation, project scaffolding, code analysis, deployment, invocation, queries, transfers, and knowledge base management. A minor gap is the lack of an explicit contract upgrade tool, though helper scripts include an upgrade script.
Maintenance
Related MCP Connectors
The OpenZeppelin Solidity Contracts MCP server integrates OpenZeppelin's security and style rules into AI-driven development workflows, enabling AI assistants to generate safe, correct, and production-ready smart contracts. It automatically validates generated code against OpenZeppelin standards (including imports, modifiers, naming conventions, and security checks) and supports various contract types including ERC-20, ERC-721, ERC-1155, Stablecoins, RWA, Governor, and Account contracts through prompt-driven workflows.
Self-hosted MCP server: 26 deterministic dev, security, and EVM tools.
MCP server for progressive tool usage at any scale (see https://klavis.ai)
The OpenZeppelin Cairo Contracts MCP server generates secure smart contracts in the Cairo language for Starknet environments based on OpenZeppelin templates. It brings OpenZeppelin's proven security and style rules directly into AI-driven development workflows to create safe, production-ready contracts. Key capabilities include providing templates for ERC-20, ERC-721, ERC-1155, Multisig, Governor, and Vesting contracts.
Related MCP Servers
- AlicenseAqualityDmaintenanceMCP server for comprehensive code analysis, navigation, and quality assessment across 25+ programming languages.988MIT
- AlicenseNot gradedqualityFmaintenanceA powerful Model Context Protocol server that creates intelligent graph representations of your codebase with comprehensive semantic analysis capabilities, supporting 11 languages and 26 MCP methods.30 npm121MIT
- AlicenseCqualityDmaintenanceAn MCP server that analyzes local or remote GitHub repositories, providing intelligent code context and structure to AI coding assistants.1013MIT
- AlicenseNot gradedqualityDmaintenanceMCP server providing AI assistants with tools for advanced EVM smart contract analysis, including proxy detection, implementation resolution, and security analysis.1MIT