Klever VM

by klever-io

Not rated
GitHub

About

MCP server for [Klever](https://klever.org) blockchain smart contract development, on-chain data exploration, and VM interaction. Public remote server available at `https://mcp.klever.org/mcp`.

Details

Author
klever-io
Categories
Developer Tools, Finance, Other

Setup

Install Klever VM in your MCP client (Claude Desktop, Cursor, Windsurf, and others).

Repository: https://github.com/klever-io/mcp-klever-vm

Follow the installation instructions in the repository README, then restart your MCP client.

- Search the Klever VM knowledge base— Query pre-loaded patterns, examples, and best practices by type, tag, or contract type usingquery_context.
- Retrieve a specific context entry— Fetch a single code example, security tip, or error pattern by its ID withget_context.
- Find similar development contexts— Discover contexts related to a given snippet or pattern viafind_similar.
- Initialize a Klever smart contract project— Scaffold a new project with build, deploy, upgrade, and query helper scripts usinginit_klever_project.
- Enhance a query with relevant Klever context— Automatically enrich a natural-language question with matching knowledge base entries viaenhance_with_context.

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.

- 🚀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

Install and run instantly via npx — no cloning required:

claude mcp add -t http klever-vm https://mcp.klever.org/mcp

SeeMCP Client Integrationfor client-specific configuration.

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/ # Documentation

- 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

- Added input validation for all endpoints
- Batch operation size limits
- Proper error responses without leaking internals
- Environment-aware error messages

- Centralized schema validation
- Proper TypeScript interfaces for options
- Runtime validation of stored data

- Batch operations using Redis MGET
- Index-based queries instead of full scans
- Optimized count operations

git clone https://github.com/klever-io/mcp-klever-vm.git cd mcp-klever-vm

- Install Klever SDK tools (required for transactions):

chmod +x scripts/install-sdk.sh && ./scripts/install-sdk.sh
# 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=development
# 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/mcp

Add to yourclaude_desktop_config.json:

{ "mcpServers": { "klever-vm": { "command": "npx", "args": ["-y", "@klever/mcp-server"] } } }

For detailed setup, see theClaude Desktop Installation Guide.

Add to your Cursor MCP settings (.cursor/mcp.json):

{ "mcpServers": { "klever-vm": { "command": "npx", "args": ["-y", "@klever/mcp-server"] } } }

Add to.vscode/mcp.jsonin your project:

{ "servers": { "klever-vm": { "type": "stdio", "command": "npx", "args": ["-y", "@klever/mcp-server"] } } }

For detailed setup, see theVS Code Installation Guide.

The Klever MCP Server can be hosted as a public shared service, allowing any developer to connect without running it locally.

# 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/mcp

The public server exposes a read-only subset of tools for security:

Write operations (add_context) and shell-based tools (init_klever_project,add_helper_scripts) are disabled in public mode.

# Build and run docker build -t mcp-klever-vm . docker run -p 3000:3000 mcp-klever-vm # Or using docker compose docker compose up -d
claude mcp add -t http klever-vm-local http://localhost:3000/mcp
pnpm install pnpm run build pnpm run start:public

- Deploy Docker container behind a reverse proxy (nginx/Caddy/cloud LB) for TLS termination
- Ensure proxy passesmcp-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)

The server automatically loads the Klever knowledge base based on your storage type:

- Knowledge isautomatically loadedwhen the server starts
- No need to runpnpm run ingestseparately
- Data exists only while server is running
- Best for development and testing

# First, ingest the knowledge base (one time) pnpm run ingest # Then start the server pnpm run dev

- Knowledge persists in Redis database
- Survives server restarts
- Best for production use

- 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

# Development mode pnpm run dev # Production mode pnpm run build && pnpm start

The HTTP API will be available athttp://localhost:3000/api

{ "type": "code_example", "content": "contract code here", "metadata": { "title": "Token Contract Example", "description": "ERC20-like token implementation", "tags": ["token", "fungible"], "contractType": "token" } }
{ "query": "transfer", "types": ["code_example", "best_practice"], "tags": ["token"], "contractType": "token", "limit": 10, "offset": 0 }

When running as MCP server, the following tools are available:

- query_context: Search for relevant Klever development context
- add_context: Add new context to the knowledge base
- get_context: Retrieve specific context by ID
- find_similar: Find contexts similar to a given context
- get_knowledge_stats: Get statistics about the knowledge base
- init_klever_project: Initialize a new Klever smart contract project with helper scripts
- enhance_with_context: Automatically enhance queries with relevant Klever VM context

- code_example: Working code snippets and examples (Rust smart contract code)
- best_practice: Recommended patterns and practices
- security_tip: Security considerations and warnings
- optimization: Performance optimization techniques
- documentation: General documentation and guides
- error_pattern: Common errors and solutions
- deployment_tool: Deployment scripts and utilities (bash scripts, tools)
- runtime_behavior: Runtime behavior explanations

The MCP server includes a comprehensive knowledge base with 95+ entries organized into 11 categories:

- Payment handling and token operations
- Decimal conversions and calculations
- Event emission and parameter rules
- CLI tool usage and best practices

- Basic contract structure templates
- Complete lottery game implementation
- Staking contract with rewards
- Cross-contract communication patterns
- Remote storage access patterns
- Token mapper helper modules

- 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 mapper selection guide with performance comparisons
- Namespace organization patterns
- View endpoints for efficient queries
- Gas optimization techniques
- OptionalValue vs Option patterns

- Input validation patterns
- Error handling strategies
- Admin and pause module usage
- Access control patterns
- Common mistakes and solutions

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();
# 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 ingest

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 suggestions

- Event annotation format (double quotes, camelCase)
- Managed type API parameters
- Zero address validation in transfers
- Optimal storage mapper selection
- Module naming conventions

Integrate with your IDE to provide context-aware suggestions for Klever contract development.

Automatically check contracts against best practices and security patterns.

Provide examples and explanations for developers learning Klever development.

Extract and organize contract documentation automatically.

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.

The MCP server includes a powerful project initialization tool that creates a new Klever smart contract project with all necessary helper scripts.

When connected via MCP, use theinit_klever_projecttool:

{ "name": "my-token-contract", "template": "empty", "noMove": false }

- name(required): The name of your contract
- template(optional): Template to use (default: "empty")
- noMove(optional): If true, keeps project in subdirectory (default: false)

The tool creates the following scripts in thescripts/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

# Via MCP tool init_klever_project({"name": "my-contract"})
./scripts/query.sh --endpoint getSum ./scripts/query.sh --endpoint getValue --arg myKey

All deployment history is tracked inoutput/history.jsonfor easy reference.

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.

Use theenhance_with_contexttool to automatically add relevant context to any query:

{ "tool": "enhance_with_context", "arguments": { "query": "How do I create a storage mapper?", "autoInclude": true } }

- 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

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.

// 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' }) });
No reviews yet — be the first

Sign in to leave a review

Use Google, GitHub, or an email account so ratings stay tied to real people.

Email sign in

No reviews posted yet.