Mcp Klever Vm

io.github.klever-io由 GitHub 帳號 klever-io 發布v1.3.0更新於 Oct 24, 2026

MCP server for Klever blockchain smart contract development.

已驗證Streamable HTTP可網頁執行資料庫知識與記憶開發者工具

概覽

AI 產生的概覽

針對 Klever 區塊鏈智慧合約開發的伺服器,讓助理取得 Klever VM 知識庫、合約分析與唯讀鏈上查詢能力。

可以做什麼
搜尋、讀取並擴充 Klever VM 知識庫條目,包含文件與知識庫統計,以及依標籤和內容尋找相似條目。分析 Klever 智慧合約 Rust 原始碼,檢查缺少的匯入、巨集、端點註解、儲存對應與事件定義等問題。查詢 Klever 鏈上資料,包括地址餘額、帳戶詳情、資產資訊、交易、區塊與驗證人清單。對智慧合約執行唯讀檢視呼叫。初始化 Klever 合約專案並加入建置、部署、升級、查詢與測試腳本。
適用情境
適合在開發、審查或學習 Klever Rust 智慧合約時,讓助理取得 Klever VM 模式、最佳實務與文件,或查看餘額、帳戶、資產、交易、區塊與驗證人等鏈上狀態。
執行需求
可連線託管的遠端端點,或以 Node.js 透過 npx 在本機執行 npm 套件。專案腳手架工具需要將 Klever SDK 安裝於 ~/klever-sdk/。自架可選用 Redis 及 MODE、PORT、STORAGE_TYPE、REDIS_URL 等環境變數。
安裝前請注意
本機版本包含在磁碟上建立專案檔案與腳本以及以 shell 為基礎的腳手架工具;託管公開伺服器停用這些工具,僅提供唯讀子集。鏈上查詢為唯讀,但部分回應為 base64 編碼,需要解碼。未宣告任何驗證或 API 金鑰。

安裝

在 SourceWeft 中

  1. 開啟 儀表板中的 Mcp Klever Vm,將其新增到工作區。
  2. 為需要使用其工具的對話啟用該服務。

Web executable,透過 Streamable HTTP。 遠端服務在工作區中設定後即可從網頁執行環境執行。

交給代理程式安裝

把這段提示詞貼上到 Claude Code、Codex、Cursor 等代理程式,或 SourceWeft 對話中。代理程式會讀取該伺服器的安裝指南,先向你展示發布者、端點和登入方式,經你同意後再把它新增到你的客戶端。金鑰不會寫進任何命令。

閱讀 https://sourceweft.com/mcp/io.github.klever-io%2Fmcp-klever-vm/install.md,並按其中說明把這個 MCP 伺服器接入我的客戶端。修改任何設定之前,先告訴我它的發布者、端點和登入方式,等我確認。不要把 API 金鑰寫進命令或我會提交的檔案;問我金鑰應從哪裡取得。

檢視代理程式所依據的安裝指南

其他 MCP 客戶端

把它新增到你客戶端的 mcpServers 設定中。

{
  "mcpServers": {
    "klever-vm": {
      "type": "http",
      "url": "https://mcp.klever.org/mcp"
    }
  }
}

README

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

Quick Start

Install and run instantly via npx — no cloning required:

bash
npx -y @klever/mcp-server

Or connect to the hosted public server:

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

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

Key Improvements Made

  1. 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
  2. API Security

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

    • Centralized schema validation
    • Proper TypeScript interfaces for options
    • Runtime validation of stored data
  4. Performance

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

Installation

  1. Clone the repository:
bash
git clone https://github.com/klever-io/mcp-klever-vm.gitcd mcp-klever-vm
  1. Install dependencies:
bash
pnpm install
  1. Copy environment configuration:
bash
cp .env.example .env
  1. Install Klever SDK tools (required for transactions):
bash
chmod +x scripts/install-sdk.sh && ./scripts/install-sdk.sh
  1. Build the project:
bash
pnpm run build

Configuration

Edit .env file to configure the server:

env
# 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

MCP Client Integration

Claude Code

bash
# Add via npx (recommended)claude mcp add klever-vm -- npx -y @klever/mcp-server
# Or connect to the public hosted serverclaude mcp add -t http klever-vm https://mcp.klever.org/mcp

Claude Desktop

Add to your claude_desktop_config.json:

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):

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

VS Code (GitHub Copilot)

Add to .vscode/mcp.json in your project:

json
{  "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

bash
# Add permanently (user-level)claude mcp add -t http klever-vm https://mcp.klever.org/mcp
# Add for current project onlyclaude mcp add -t http -s project klever-vm https://mcp.klever.org/mcp

Available Tools (Public Mode)

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

ToolDescription
query_contextSearch the Klever VM knowledge base
get_contextRetrieve a specific context by ID
find_similarFind contexts similar to a given context
get_knowledge_statsGet knowledge base statistics
enhance_with_contextEnhance 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

bash
# Build and rundocker build -t mcp-klever-vm .docker run -p 3000:3000 mcp-klever-vm
# Or using docker composedocker compose up -d

Then connect:

bash
claude mcp add -t http klever-vm-local http://localhost:3000/mcp

Self-Hosting without Docker

bash
pnpm installpnpm run buildpnpm run start:public

Environment Variables (Public Mode)

VariableDefaultDescription
MODEhttpSet to public for hosted mode
PORT3000Server port
CORS_ORIGINS(unset)Comma-separated allowed origins. Unset or * allows all origins
RATE_LIMIT_MCP60MCP endpoint requests/min per IP
RATE_LIMIT_API30API endpoint requests/min per IP
BODY_SIZE_LIMIT1mbMax 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-id header 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 ingest separately
  • Data exists only while server is running
  • Best for development and testing
Redis Storage
bash
# First, ingest the knowledge base (one time)pnpm run ingest
# Then start the serverpnpm run dev
  • Knowledge 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

bash
# Development modepnpm run dev
# Production modepnpm run build && pnpm start

The HTTP API will be available at http://localhost:3000/api

Running as MCP Server

bash
MODE=mcp pnpm start

Use with any MCP-compatible client.

API Endpoints

POST /api/context

Ingest new context into the system.

json
{  "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.

json
{  "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 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

Context Types

  • 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

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:

typescript
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 contractawait ingester.ingestContract('./path/to/contract.rs', 'AuthorName');
// Ingest entire directoryawait ingester.ingestDirectory('./contracts', 'AuthorName');
// Add common patternsawait ingester.ingestCommonPatterns();

Development

bash
# Run testspnpm test
# Lint codepnpm run lint
# Format codepnpm run format
# Watch modepnpm run dev
# Ingest/update knowledge basepnpm run ingest

Contract Validation

The server can automatically validate Klever contracts and detect issues:

typescript
import { KleverValidator } from './parsers/validators.js';
const issues = KleverValidator.validateContract(contractCode);// Returns array of detected issues with suggestions

Validation 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:

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

Parameters:

  • name (required): The name of your contract
  • template (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

  1. Initialize project:

    bash
    # Via MCP toolinit_klever_project({"name": "my-contract"})
  2. Build contract:

    bash
    ./scripts/build.sh
  3. Deploy to testnet:

    bash
    ./scripts/deploy.sh
  4. Query contract:

    bash
    ./scripts/query.sh --endpoint getSum./scripts/query.sh --endpoint getValue --arg myKey
  5. Upgrade contract:

    bash
    ./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:

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

This will:

  1. Extract relevant keywords from the query
  2. Search the knowledge base for matching contexts
  3. Return an enhanced query with context included
  4. Provide metadata about what was found

Integration Pattern

For MCP clients that want to always check Klever context first:

javascript
// Always enhance Klever-related queriesif (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

typescript
// Query for token transfer examplesconst 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

bash
# Using curl to add contextcurl -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:

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests
  5. Submit a pull request

License

MIT License - see LICENSE file for details

Acknowledgments

來源:README.md,提交 df0f02c

工具

16

query_context

Query Knowledge Base

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.

輸入參數tagslimitquerytypesoffsetcontractType

get_context

Get Context by ID

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.

輸入參數id必填

find_similar

Find Similar Contexts

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.

輸入參數id必填limit

get_knowledge_stats

Knowledge Base Stats

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.

無需輸入參數。

enhance_with_context

Enhance Query with Context

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.

輸入參數query必填autoInclude

search_documentation

Search Documentation

Search Klever VM documentation and knowledge base. Returns human-readable markdown with titles, descriptions, and code snippets. Optimized for "how do I..." questions. Use this instead of query_context when you need formatted developer documentation.

輸入參數query必填category

analyze_contract

Analyze Contract

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.

輸入參數sourceCode必填contractName

get_balance

Get Balance

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.

輸入參數address必填assetIdnetwork

get_account

Get Account

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.

輸入參數address必填network

get_asset_info

Get Asset Info

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.

輸入參數assetId必填network

query_sc

Query Smart Contract

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.

輸入參數argscallernetworkfuncName必填scAddress必填

get_transaction

Get Transaction

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.

輸入參數hash必填network

get_block

Get Block

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.

輸入參數noncenetwork

list_validators

List Validators

List active validators on the Klever blockchain network. Returns validator addresses, names, commission rates, delegation info, and staking amounts.

輸入參數network

init_klever_project

Initialize Klever Project

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. NOTE: In public profile, this tool returns a project template JSON and does not perform any filesystem changes.

輸入參數name必填noMovetemplate

add_helper_scripts

Add Helper Scripts

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). NOTE: In public profile, this tool returns a project template JSON and does not perform any filesystem changes.

輸入參數contractName

版本歷史

1
  1. v1.3.0最新Sep 16, 2026

評分

已滿足適用檢查項的 100%

該評分衡量此收錄條目的完整程度,依據註冊中心條目、端點與公開來源計算得出。它不是對伺服器本身的評價,也不表示伺服器安全或目前可用:可連通性是帶日期的檢查結果,評分也不包含安裝量或使用者評價。

  • 近 30 天內可連通必需25 分
  • 已宣告認證方式必需10 分
  • 已列出工具必需15 分
  • 描述必需15 分
  • 圖示10 分
  • 文件15 分
  • 授權條款10 分