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
Add this skill
npx mdskills install klever-io/mcp-klever-vmComprehensive blockchain development MCP with 95+ knowledge entries, flexible storage, and multi-mode operation
1# Klever MCP Server23A 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.45## Features67- ๐ **Triple Mode Operation**: Run as HTTP API server, MCP stdio server, or public hosted MCP server8- ๐พ **Flexible Storage**: In-memory or Redis backend support9- ๐ **Smart Context Retrieval**: Query by type, tags, or contract type10- ๐ **Automatic Pattern Extraction**: Parse Klever contracts to extract examples and patterns11- ๐ฏ **Relevance Ranking**: Intelligent scoring and ranking of context12- ๐ **Live Updates**: Add and update context in real-time13- ๐ก๏ธ **Type Safety**: Full TypeScript with Zod validation14- ๐ **Comprehensive Knowledge Base**: Pre-loaded with Klever VM patterns, best practices, and examples15- ๐ง **Contract Validation**: Automatic detection of common issues and anti-patterns16- ๐ **Deployment Scripts**: Ready-to-use scripts for contract deployment, upgrade, and querying1718## Quick Start1920Install and run instantly via npx โ no cloning required:2122```bash23npx -y @klever/mcp-server24```2526Or connect to the hosted public server:2728```bash29claude mcp add -t http klever-vm https://mcp.klever.org/mcp30```3132See [MCP Client Integration](#mcp-client-integration) for client-specific configuration.3334## Architecture3536```37mcp-klever-vm/38โโโ src/39โ โโโ api/ # HTTP API routes with validation40โ โโโ context/ # Context management service layer41โ โโโ mcp/ # MCP protocol server implementation42โ โโโ parsers/ # Klever contract parser and validator43โ โโโ storage/ # Storage backends (memory/Redis)44โ โ โโโ memory.ts # In-memory storage with size limits45โ โ โโโ redis.ts # Redis storage with optimized queries46โ โโโ types/ # TypeScript type definitions47โ โโโ utils/ # Utilities and ingestion tools48โ โโโ knowledge/ # Modular knowledge base (95+ entries)49โ โโโ core/ # Core concepts and imports50โ โโโ storage/ # Storage patterns and mappers51โ โโโ events/ # Event handling and rules52โ โโโ tokens/ # Token operations and decimals53โ โโโ modules/ # Built-in modules (admin, pause)54โ โโโ tools/ # CLI tools (koperator, ksc)55โ โโโ scripts/ # Helper scripts56โ โโโ examples/ # Complete contract examples57โ โโโ errors/ # Error patterns58โ โโโ best-practices/ # Optimization and validation59โ โโโ documentation/ # API reference60โโโ tests/ # Test files61โโโ docs/ # Documentation62```6364### Key Improvements Made65661. **Storage Layer**67 - Added memory limits to prevent OOM in InMemoryStorage68 - Optimized Redis queries to avoid O(N) KEYS command69 - Added atomic transactions for Redis operations70 - Improved error handling and validation71722. **API Security**73 - Added input validation for all endpoints74 - Batch operation size limits75 - Proper error responses without leaking internals76 - Environment-aware error messages77783. **Type Safety**79 - Centralized schema validation80 - Proper TypeScript interfaces for options81 - Runtime validation of stored data82834. **Performance**84 - Batch operations using Redis MGET85 - Index-based queries instead of full scans86 - Optimized count operations8788## Installation89901. Clone the repository:91```bash92git clone https://github.com/klever-io/mcp-klever-vm.git93cd mcp-klever-vm94```95962. Install dependencies:97```bash98pnpm install99```1001013. Copy environment configuration:102```bash103cp .env.example .env104```1051064. Install Klever SDK tools (required for transactions):107```bash108chmod +x scripts/install-sdk.sh && ./scripts/install-sdk.sh109```1101115. Build the project:112```bash113pnpm run build114```115116## Configuration117118Edit `.env` file to configure the server:119120```env121# Server Mode (http, mcp, or public)122MODE=http123124# HTTP Server Port (only for http mode)125PORT=3000126127# Storage Backend (memory or redis)128STORAGE_TYPE=memory129130# Maximum contexts for in-memory storage (default: 10000)131MEMORY_MAX_SIZE=10000132133# Redis URL (only if STORAGE_TYPE=redis)134REDIS_URL=redis://localhost:6379135136# Node environment (development or production)137NODE_ENV=development138```139140## MCP Client Integration141142### Claude Code143144```bash145# Add via npx (recommended)146claude mcp add klever-vm -- npx -y @klever/mcp-server147148# Or connect to the public hosted server149claude mcp add -t http klever-vm https://mcp.klever.org/mcp150```151152### Claude Desktop153154Add to your `claude_desktop_config.json`:155156```json157{158 "mcpServers": {159 "klever-vm": {160 "command": "npx",161 "args": ["-y", "@klever/mcp-server"]162 }163 }164}165```166167For detailed setup, see the [Claude Desktop Installation Guide](docs/install-claude.md).168169### Cursor170171Add to your Cursor MCP settings (`.cursor/mcp.json`):172173```json174{175 "mcpServers": {176 "klever-vm": {177 "command": "npx",178 "args": ["-y", "@klever/mcp-server"]179 }180 }181}182```183184### VS Code (GitHub Copilot)185186Add to `.vscode/mcp.json` in your project:187188```json189{190 "servers": {191 "klever-vm": {192 "type": "stdio",193 "command": "npx",194 "args": ["-y", "@klever/mcp-server"]195 }196 }197}198```199200For detailed setup, see the [VS Code Installation Guide](docs/install-vscode.md).201202## Public MCP Server203204The Klever MCP Server can be hosted as a public shared service, allowing any developer to connect without running it locally.205206### Connecting to the Public Server207208```bash209# Add permanently (user-level)210claude mcp add -t http klever-vm https://mcp.klever.org/mcp211212# Add for current project only213claude mcp add -t http -s project klever-vm https://mcp.klever.org/mcp214```215216### Available Tools (Public Mode)217218The public server exposes a read-only subset of tools for security:219220| Tool | Description |221|------|-------------|222| `query_context` | Search the Klever VM knowledge base |223| `get_context` | Retrieve a specific context by ID |224| `find_similar` | Find contexts similar to a given context |225| `get_knowledge_stats` | Get knowledge base statistics |226| `enhance_with_context` | Enhance queries with relevant Klever VM context |227228Write operations (`add_context`) and shell-based tools (`init_klever_project`, `add_helper_scripts`) are disabled in public mode.229230### Self-Hosting with Docker231232```bash233# Build and run234docker build -t mcp-klever-vm .235docker run -p 3000:3000 mcp-klever-vm236237# Or using docker compose238docker compose up -d239```240241Then connect:242```bash243claude mcp add -t http klever-vm-local http://localhost:3000/mcp244```245246### Self-Hosting without Docker247248```bash249pnpm install250pnpm run build251pnpm run start:public252```253254### Environment Variables (Public Mode)255256| Variable | Default | Description |257|----------|---------|-------------|258| `MODE` | `http` | Set to `public` for hosted mode |259| `PORT` | `3000` | Server port |260| `CORS_ORIGINS` | _(unset)_ | Comma-separated allowed origins. Unset or `*` allows all origins |261| `RATE_LIMIT_MCP` | `60` | MCP endpoint requests/min per IP |262| `RATE_LIMIT_API` | `30` | API endpoint requests/min per IP |263| `BODY_SIZE_LIMIT` | `1mb` | Max request body size |264265### Deployment Notes266267For production at `mcp.klever.org`:268- Deploy Docker container behind a reverse proxy (nginx/Caddy/cloud LB) for TLS termination269- Ensure proxy passes `mcp-session-id` header and supports SSE (disable response buffering)270- Single instance is sufficient as the server is read-only with an in-memory knowledge base271- Consider Cloudflare for DDoS protection (SSE is supported)272273## Usage274275### Knowledge Base Loading276277The server automatically loads the Klever knowledge base based on your storage type:278279#### Memory Storage (Default)280- Knowledge is **automatically loaded** when the server starts281- No need to run `pnpm run ingest` separately282- Data exists only while server is running283- Best for development and testing284285#### Redis Storage286```bash287# First, ingest the knowledge base (one time)288pnpm run ingest289290# Then start the server291pnpm run dev292```293- Knowledge persists in Redis database294- Survives server restarts295- Best for production use296297This will load:298- Smart contract templates and examples299- Annotation rules and best practices300- Storage mapper patterns and comparisons301- Deployment and query scripts302- Common errors and solutions303- Testing patterns304- API reference documentation305306### Running as HTTP Server307308```bash309# Development mode310pnpm run dev311312# Production mode313pnpm run build && pnpm start314```315316The HTTP API will be available at `http://localhost:3000/api`317318### Running as MCP Server319320```bash321MODE=mcp pnpm start322```323324Use with any MCP-compatible client.325326### API Endpoints327328#### POST `/api/context`329Ingest new context into the system.330331```json332{333 "type": "code_example",334 "content": "contract code here",335 "metadata": {336 "title": "Token Contract Example",337 "description": "ERC20-like token implementation",338 "tags": ["token", "fungible"],339 "contractType": "token"340 }341}342```343344#### GET `/api/context/:id`345Retrieve specific context by ID.346347#### POST `/api/context/query`348Query contexts with filters.349350```json351{352 "query": "transfer",353 "types": ["code_example", "best_practice"],354 "tags": ["token"],355 "contractType": "token",356 "limit": 10,357 "offset": 0358}359```360361#### PUT `/api/context/:id`362Update existing context.363364#### DELETE `/api/context/:id`365Delete context.366367#### GET `/api/context/:id/similar`368Find similar contexts.369370#### POST `/api/context/batch`371Batch ingest multiple contexts.372373### MCP Tools374375When running as MCP server, the following tools are available:376377- `query_context`: Search for relevant Klever development context378- `add_context`: Add new context to the knowledge base379- `get_context`: Retrieve specific context by ID380- `find_similar`: Find contexts similar to a given context381- `get_knowledge_stats`: Get statistics about the knowledge base382- `init_klever_project`: Initialize a new Klever smart contract project with helper scripts383- `enhance_with_context`: Automatically enhance queries with relevant Klever VM context384385## Context Types386387- `code_example`: Working code snippets and examples (Rust smart contract code)388- `best_practice`: Recommended patterns and practices389- `security_tip`: Security considerations and warnings390- `optimization`: Performance optimization techniques391- `documentation`: General documentation and guides392- `error_pattern`: Common errors and solutions393- `deployment_tool`: Deployment scripts and utilities (bash scripts, tools)394- `runtime_behavior`: Runtime behavior explanations395396## Pre-loaded Knowledge Base397398The MCP server includes a comprehensive knowledge base with 95+ entries organized into 11 categories:399400### Critical Patterns401- Payment handling and token operations402- Decimal conversions and calculations403- Event emission and parameter rules404- CLI tool usage and best practices405406### Contract Patterns & Examples407- Basic contract structure templates408- Complete lottery game implementation409- Staking contract with rewards410- Cross-contract communication patterns411- Remote storage access patterns412- Token mapper helper modules413414### Development Tools415- **Koperator**: Complete CLI reference with argument encoding416- **KSC**: Build commands and project setup417- Deployment, upgrade, and query scripts418- Interactive contract management tools419- Common utilities library (bech32, network management)420421### Storage & Optimization422- Storage mapper selection guide with performance comparisons423- Namespace organization patterns424- View endpoints for efficient queries425- Gas optimization techniques426- OptionalValue vs Option patterns427428### Best Practices & Security429- Input validation patterns430- Error handling strategies431- Admin and pause module usage432- Access control patterns433- Common mistakes and solutions434435## Ingesting Contracts436437Use the built-in ingestion utilities to parse and import Klever contracts:438439```typescript440import { StorageFactory } from './storage/index.js';441import { ContextService } from './context/service.js';442import { ContractIngester } from './utils/ingest.js';443444const storage = StorageFactory.create('memory');445const contextService = new ContextService(storage);446const ingester = new ContractIngester(contextService);447448// Ingest a single contract449await ingester.ingestContract('./path/to/contract.rs', 'AuthorName');450451// Ingest entire directory452await ingester.ingestDirectory('./contracts', 'AuthorName');453454// Add common patterns455await ingester.ingestCommonPatterns();456```457458## Development459460```bash461# Run tests462pnpm test463464# Lint code465pnpm run lint466467# Format code468pnpm run format469470# Watch mode471pnpm run dev472473# Ingest/update knowledge base474pnpm run ingest475```476477## Contract Validation478479The server can automatically validate Klever contracts and detect issues:480481```typescript482import { KleverValidator } from './parsers/validators.js';483484const issues = KleverValidator.validateContract(contractCode);485// Returns array of detected issues with suggestions486```487488Validation checks include:489- Event annotation format (double quotes, camelCase)490- Managed type API parameters491- Zero address validation in transfers492- Optimal storage mapper selection493- Module naming conventions494495## Example Use Cases496497### 1. Smart Contract Development Assistant498Integrate with your IDE to provide context-aware suggestions for Klever contract development.499500### 2. Code Review Tool501Automatically check contracts against best practices and security patterns.502503### 3. Learning Platform504Provide examples and explanations for developers learning Klever development.505506### 4. Documentation Generator507Extract and organize contract documentation automatically.508509## Project Specifications and Examples510511For complete project implementation examples and specifications, see:512- [Project Specification Template](docs/project-specification-template.md) - 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.513514## Project Initialization515516The MCP server includes a powerful project initialization tool that creates a new Klever smart contract project with all necessary helper scripts.517518### Using the init_klever_project Tool519520When connected via MCP, use the `init_klever_project` tool:521522```json523{524 "name": "my-token-contract",525 "template": "empty",526 "noMove": false527}528```529530Parameters:531- `name` (required): The name of your contract532- `template` (optional): Template to use (default: "empty")533- `noMove` (optional): If true, keeps project in subdirectory (default: false)534535### Generated Helper Scripts536537The tool creates the following scripts in the `scripts/` directory:538539- **build.sh**: Builds the smart contract540- **deploy.sh**: Deploys to Klever testnet with auto-detection of contract artifacts541- **upgrade.sh**: Upgrades existing contract (auto-detects from history.json)542- **query.sh**: Query contract endpoints with proper encoding/decoding543- **test.sh**: Run contract tests544- **interact.sh**: Shows usage examples and available commands545546### Example Workflow5475481. Initialize project:549 ```bash550 # Via MCP tool551 init_klever_project({"name": "my-contract"})552 ```5535542. Build contract:555 ```bash556 ./scripts/build.sh557 ```5585593. Deploy to testnet:560 ```bash561 ./scripts/deploy.sh562 ```5635644. Query contract:565 ```bash566 ./scripts/query.sh --endpoint getSum567 ./scripts/query.sh --endpoint getValue --arg myKey568 ```5695705. Upgrade contract:571 ```bash572 ./scripts/upgrade.sh573 ```574575All deployment history is tracked in `output/history.json` for easy reference.576577## Automatic Context Enhancement578579The MCP server can automatically enhance queries with relevant Klever VM context. This ensures your MCP client always has access to the most relevant information.580581### Using Context Enhancement582583Use the `enhance_with_context` tool to automatically add relevant context to any query:584585```json586{587 "tool": "enhance_with_context",588 "arguments": {589 "query": "How do I create a storage mapper?",590 "autoInclude": true591 }592}593```594595This will:5961. Extract relevant keywords from the query5972. Search the knowledge base for matching contexts5983. Return an enhanced query with context included5994. Provide metadata about what was found600601### Integration Pattern602603For MCP clients that want to always check Klever context first:604605```javascript606// Always enhance Klever-related queries607if (query.match(/klever|kvm|smart contract|endpoint/i)) {608 const enhanced = await callTool('enhance_with_context', { query });609 // Use enhanced.enhancedQuery for processing610}611```612613The context enhancement feature automatically enriches queries with relevant Klever VM knowledge from the comprehensive knowledge base.614615## Integration Examples616617### VS Code Extension618```typescript619// Query for token transfer examples620const response = await fetch('http://localhost:3000/api/context/query', {621 method: 'POST',622 headers: { 'Content-Type': 'application/json' },623 body: JSON.stringify({624 query: 'transfer',625 types: ['code_example'],626 contractType: 'token'627 })628});629```630631### CLI Tool632```bash633# Using curl to add context634curl -X POST http://localhost:3000/api/context \635 -H "Content-Type: application/json" \636 -d '{637 "type": "security_tip",638 "content": "Always check for zero address",639 "metadata": {640 "title": "Zero Address Check",641 "tags": ["security", "validation"]642 }643 }'644```645646## Contributing647648Contributions are welcome! Please:6491. Fork the repository6502. Create a feature branch6513. Make your changes6524. Add tests6535. Submit a pull request654655## License656657MIT License - see LICENSE file for details658659## Acknowledgments660661- Inspired by [Context7 by Upstash](https://github.com/upstash/context7)662- Built for the [Klever Blockchain](https://klever.io)663- Uses the [Klever VM SDK (Rust)](https://github.com/klever-io/klever-vm-sdk-rs)
Full transparency โ inspect the skill content before installing.