{
  "markdown": "# Klever MCP Server\n\nA 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.\n\n## Features\n\n- 🚀 **Triple Mode Operation**: Run as HTTP API server, MCP stdio server, or public hosted MCP server\n- 💾 **Flexible Storage**: In-memory or Redis backend support\n- 🔍 **Smart Context Retrieval**: Query by type, tags, or contract type\n- 📝 **Automatic Pattern Extraction**: Parse Klever contracts to extract examples and patterns\n- 🎯 **Relevance Ranking**: Intelligent scoring and ranking of context\n- 🔄 **Live Updates**: Add and update context in real-time\n- 🛡️ **Type Safety**: Full TypeScript with Zod validation\n- 📚 **Comprehensive Knowledge Base**: Pre-loaded with Klever VM patterns, best practices, and examples\n- 🔧 **Contract Validation**: Automatic detection of common issues and anti-patterns\n- 🚀 **Deployment Scripts**: Ready-to-use scripts for contract deployment, upgrade, and querying\n\n## Quick Start\n\nInstall and run instantly via npx — no cloning required:\n\n```bash\nnpx -y @klever/mcp-server\n```\n\nOr connect to the hosted public server:\n\n```bash\nclaude mcp add -t http klever-vm https://mcp.klever.org/mcp\n```\n\nSee [MCP Client Integration](#mcp-client-integration) for client-specific configuration.\n\n## Architecture\n\n```\nmcp-klever-vm/\n├── src/\n│   ├── api/          # HTTP API routes with validation\n│   ├── context/      # Context management service layer\n│   ├── mcp/          # MCP protocol server implementation\n│   ├── parsers/      # Klever contract parser and validator\n│   ├── storage/      # Storage backends (memory/Redis)\n│   │   ├── memory.ts # In-memory storage with size limits\n│   │   └── redis.ts  # Redis storage with optimized queries\n│   ├── types/        # TypeScript type definitions\n│   ├── utils/        # Utilities and ingestion tools\n│   └── knowledge/    # Modular knowledge base (95+ entries)\n│       ├── core/     # Core concepts and imports\n│       ├── storage/  # Storage patterns and mappers\n│       ├── events/   # Event handling and rules\n│       ├── tokens/   # Token operations and decimals\n│       ├── modules/  # Built-in modules (admin, pause)\n│       ├── tools/    # CLI tools (koperator, ksc)\n│       ├── scripts/  # Helper scripts\n│       ├── examples/ # Complete contract examples\n│       ├── errors/   # Error patterns\n│       ├── best-practices/ # Optimization and validation\n│       └── documentation/  # API reference\n├── tests/            # Test files\n└── docs/             # Documentation\n```\n\n### Key Improvements Made\n\n1. **Storage Layer**\n   - Added memory limits to prevent OOM in InMemoryStorage\n   - Optimized Redis queries to avoid O(N) KEYS command\n   - Added atomic transactions for Redis operations\n   - Improved error handling and validation\n\n2. **API Security**\n   - Added input validation for all endpoints\n   - Batch operation size limits\n   - Proper error responses without leaking internals\n   - Environment-aware error messages\n\n3. **Type Safety**\n   - Centralized schema validation\n   - Proper TypeScript interfaces for options\n   - Runtime validation of stored data\n\n4. **Performance**\n   - Batch operations using Redis MGET\n   - Index-based queries instead of full scans\n   - Optimized count operations\n\n## Installation\n\n1. Clone the repository:\n```bash\ngit clone https://github.com/klever-io/mcp-klever-vm.git\ncd mcp-klever-vm\n```\n\n2. Install dependencies:\n```bash\npnpm install\n```\n\n3. Copy environment configuration:\n```bash\ncp .env.example .env\n```\n\n4. Install Klever SDK tools (required for transactions):\n```bash\nchmod +x scripts/install-sdk.sh && ./scripts/install-sdk.sh\n```\n\n5. Build the project:\n```bash\npnpm run build\n```\n\n## Configuration\n\nEdit `.env` file to configure the server:\n\n```env\n# Server Mode (http, mcp, or public)\nMODE=http\n\n# HTTP Server Port (only for http mode)\nPORT=3000\n\n# Storage Backend (memory or redis)\nSTORAGE_TYPE=memory\n\n# Maximum contexts for in-memory storage (default: 10000)\nMEMORY_MAX_SIZE=10000\n\n# Redis URL (only if STORAGE_TYPE=redis)\nREDIS_URL=redis://localhost:6379\n\n# Node environment (development or production)\nNODE_ENV=development\n```\n\n## MCP Client Integration\n\n### Claude Code\n\n```bash\n# Add via npx (recommended)\nclaude mcp add klever-vm -- npx -y @klever/mcp-server\n\n# Or connect to the public hosted server\nclaude mcp add -t http klever-vm https://mcp.klever.org/mcp\n```\n\n### Claude Desktop\n\nAdd to your `claude_desktop_config.json`:\n\n```json\n{\n  \"mcpServers\": {\n    \"klever-vm\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@klever/mcp-server\"]\n    }\n  }\n}\n```\n\nFor detailed setup, see the [Claude Desktop Installation Guide](docs/install-claude.md).\n\n### Cursor\n\nAdd to your Cursor MCP settings (`.cursor/mcp.json`):\n\n```json\n{\n  \"mcpServers\": {\n    \"klever-vm\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@klever/mcp-server\"]\n    }\n  }\n}\n```\n\n### VS Code (GitHub Copilot)\n\nAdd to `.vscode/mcp.json` in your project:\n\n```json\n{\n  \"servers\": {\n    \"klever-vm\": {\n      \"type\": \"stdio\",\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@klever/mcp-server\"]\n    }\n  }\n}\n```\n\nFor detailed setup, see the [VS Code Installation Guide](docs/install-vscode.md).\n\n## Public MCP Server\n\nThe Klever MCP Server can be hosted as a public shared service, allowing any developer to connect without running it locally.\n\n### Connecting to the Public Server\n\n```bash\n# Add permanently (user-level)\nclaude mcp add -t http klever-vm https://mcp.klever.org/mcp\n\n# Add for current project only\nclaude mcp add -t http -s project klever-vm https://mcp.klever.org/mcp\n```\n\n### Available Tools (Public Mode)\n\nThe public server exposes a read-only subset of tools for security:\n\n| Tool | Description |\n|------|-------------|\n| `query_context` | Search the Klever VM knowledge base |\n| `get_context` | Retrieve a specific context by ID |\n| `find_similar` | Find contexts similar to a given context |\n| `get_knowledge_stats` | Get knowledge base statistics |\n| `enhance_with_context` | Enhance queries with relevant Klever VM context |\n\nWrite operations (`add_context`) and shell-based tools (`init_klever_project`, `add_helper_scripts`) are disabled in public mode.\n\n### Self-Hosting with Docker\n\n```bash\n# Build and run\ndocker build -t mcp-klever-vm .\ndocker run -p 3000:3000 mcp-klever-vm\n\n# Or using docker compose\ndocker compose up -d\n```\n\nThen connect:\n```bash\nclaude mcp add -t http klever-vm-local http://localhost:3000/mcp\n```\n\n### Self-Hosting without Docker\n\n```bash\npnpm install\npnpm run build\npnpm run start:public\n```\n\n### Environment Variables (Public Mode)\n\n| Variable | Default | Description |\n|----------|---------|-------------|\n| `MODE` | `http` | Set to `public` for hosted mode |\n| `PORT` | `3000` | Server port |\n| `CORS_ORIGINS` | _(unset)_ | Comma-separated allowed origins. Unset or `*` allows all origins |\n| `RATE_LIMIT_MCP` | `60` | MCP endpoint requests/min per IP |\n| `RATE_LIMIT_API` | `30` | API endpoint requests/min per IP |\n| `BODY_SIZE_LIMIT` | `1mb` | Max request body size |\n\n### Deployment Notes\n\nFor production at `mcp.klever.org`:\n- Deploy Docker container behind a reverse proxy (nginx/Caddy/cloud LB) for TLS termination\n- Ensure proxy passes `mcp-session-id` header and supports SSE (disable response buffering)\n- Single instance is sufficient as the server is read-only with an in-memory knowledge base\n- Consider Cloudflare for DDoS protection (SSE is supported)\n\n## Usage\n\n### Knowledge Base Loading\n\nThe server automatically loads the Klever knowledge base based on your storage type:\n\n#### Memory Storage (Default)\n- Knowledge is **automatically loaded** when the server starts\n- No need to run `pnpm run ingest` separately\n- Data exists only while server is running\n- Best for development and testing\n\n#### Redis Storage\n```bash\n# First, ingest the knowledge base (one time)\npnpm run ingest\n\n# Then start the server\npnpm run dev\n```\n- Knowledge persists in Redis database\n- Survives server restarts\n- Best for production use\n\nThis will load:\n- Smart contract templates and examples\n- Annotation rules and best practices\n- Storage mapper patterns and comparisons\n- Deployment and query scripts\n- Common errors and solutions\n- Testing patterns\n- API reference documentation\n\n### Running as HTTP Server\n\n```bash\n# Development mode\npnpm run dev\n\n# Production mode\npnpm run build && pnpm start\n```\n\nThe HTTP API will be available at `http://localhost:3000/api`\n\n### Running as MCP Server\n\n```bash\nMODE=mcp pnpm start\n```\n\nUse with any MCP-compatible client.\n\n### API Endpoints\n\n#### POST `/api/context`\nIngest new context into the system.\n\n```json\n{\n  \"type\": \"code_example\",\n  \"content\": \"contract code here\",\n  \"metadata\": {\n    \"title\": \"Token Contract Example\",\n    \"description\": \"ERC20-like token implementation\",\n    \"tags\": [\"token\", \"fungible\"],\n    \"contractType\": \"token\"\n  }\n}\n```\n\n#### GET `/api/context/:id`\nRetrieve specific context by ID.\n\n#### POST `/api/context/query`\nQuery contexts with filters.\n\n```json\n{\n  \"query\": \"transfer\",\n  \"types\": [\"code_example\", \"best_practice\"],\n  \"tags\": [\"token\"],\n  \"contractType\": \"token\",\n  \"limit\": 10,\n  \"offset\": 0\n}\n```\n\n#### PUT `/api/context/:id`\nUpdate existing context.\n\n#### DELETE `/api/context/:id`\nDelete context.\n\n#### GET `/api/context/:id/similar`\nFind similar contexts.\n\n#### POST `/api/context/batch`\nBatch ingest multiple contexts.\n\n### MCP Tools\n\nWhen running as MCP server, the following tools are available:\n\n- `query_context`: Search for relevant Klever development context\n- `add_context`: Add new context to the knowledge base\n- `get_context`: Retrieve specific context by ID\n- `find_similar`: Find contexts similar to a given context\n- `get_knowledge_stats`: Get statistics about the knowledge base\n- `init_klever_project`: Initialize a new Klever smart contract project with helper scripts\n- `enhance_with_context`: Automatically enhance queries with relevant Klever VM context\n\n## Context Types\n\n- `code_example`: Working code snippets and examples (Rust smart contract code)\n- `best_practice`: Recommended patterns and practices\n- `security_tip`: Security considerations and warnings\n- `optimization`: Performance optimization techniques\n- `documentation`: General documentation and guides\n- `error_pattern`: Common errors and solutions\n- `deployment_tool`: Deployment scripts and utilities (bash scripts, tools)\n- `runtime_behavior`: Runtime behavior explanations\n\n## Pre-loaded Knowledge Base\n\nThe MCP server includes a comprehensive knowledge base with 95+ entries organized into 11 categories:\n\n### Critical Patterns\n- Payment handling and token operations\n- Decimal conversions and calculations\n- Event emission and parameter rules\n- CLI tool usage and best practices\n\n### Contract Patterns & Examples\n- Basic contract structure templates\n- Complete lottery game implementation\n- Staking contract with rewards\n- Cross-contract communication patterns\n- Remote storage access patterns\n- Token mapper helper modules\n\n### Development Tools\n- **Koperator**: Complete CLI reference with argument encoding\n- **KSC**: Build commands and project setup\n- Deployment, upgrade, and query scripts\n- Interactive contract management tools\n- Common utilities library (bech32, network management)\n\n### Storage & Optimization\n- Storage mapper selection guide with performance comparisons\n- Namespace organization patterns\n- View endpoints for efficient queries\n- Gas optimization techniques\n- OptionalValue vs Option patterns\n\n### Best Practices & Security\n- Input validation patterns\n- Error handling strategies\n- Admin and pause module usage\n- Access control patterns\n- Common mistakes and solutions\n\n## Ingesting Contracts\n\nUse the built-in ingestion utilities to parse and import Klever contracts:\n\n```typescript\nimport { StorageFactory } from './storage/index.js';\nimport { ContextService } from './context/service.js';\nimport { ContractIngester } from './utils/ingest.js';\n\nconst storage = StorageFactory.create('memory');\nconst contextService = new ContextService(storage);\nconst ingester = new ContractIngester(contextService);\n\n// Ingest a single contract\nawait ingester.ingestContract('./path/to/contract.rs', 'AuthorName');\n\n// Ingest entire directory\nawait ingester.ingestDirectory('./contracts', 'AuthorName');\n\n// Add common patterns\nawait ingester.ingestCommonPatterns();\n```\n\n## Development\n\n```bash\n# Run tests\npnpm test\n\n# Lint code\npnpm run lint\n\n# Format code\npnpm run format\n\n# Watch mode\npnpm run dev\n\n# Ingest/update knowledge base\npnpm run ingest\n```\n\n## Contract Validation\n\nThe server can automatically validate Klever contracts and detect issues:\n\n```typescript\nimport { KleverValidator } from './parsers/validators.js';\n\nconst issues = KleverValidator.validateContract(contractCode);\n// Returns array of detected issues with suggestions\n```\n\nValidation checks include:\n- Event annotation format (double quotes, camelCase)\n- Managed type API parameters\n- Zero address validation in transfers\n- Optimal storage mapper selection\n- Module naming conventions\n\n## Example Use Cases\n\n### 1. Smart Contract Development Assistant\nIntegrate with your IDE to provide context-aware suggestions for Klever contract development.\n\n### 2. Code Review Tool\nAutomatically check contracts against best practices and security patterns.\n\n### 3. Learning Platform\nProvide examples and explanations for developers learning Klever development.\n\n### 4. Documentation Generator\nExtract and organize contract documentation automatically.\n\n## Project Specifications and Examples\n\nFor complete project implementation examples and specifications, see:\n- [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.\n\n## Project Initialization\n\nThe MCP server includes a powerful project initialization tool that creates a new Klever smart contract project with all necessary helper scripts.\n\n### Using the init_klever_project Tool\n\nWhen connected via MCP, use the `init_klever_project` tool:\n\n```json\n{\n  \"name\": \"my-token-contract\",\n  \"template\": \"empty\",\n  \"noMove\": false\n}\n```\n\nParameters:\n- `name` (required): The name of your contract\n- `template` (optional): Template to use (default: \"empty\")\n- `noMove` (optional): If true, keeps project in subdirectory (default: false)\n\n### Generated Helper Scripts\n\nThe tool creates the following scripts in the `scripts/` directory:\n\n- **build.sh**: Builds the smart contract\n- **deploy.sh**: Deploys to Klever testnet with auto-detection of contract artifacts\n- **upgrade.sh**: Upgrades existing contract (auto-detects from history.json)\n- **query.sh**: Query contract endpoints with proper encoding/decoding\n- **test.sh**: Run contract tests\n- **interact.sh**: Shows usage examples and available commands\n\n### Example Workflow\n\n1. Initialize project:\n   ```bash\n   # Via MCP tool\n   init_klever_project({\"name\": \"my-contract\"})\n   ```\n\n2. Build contract:\n   ```bash\n   ./scripts/build.sh\n   ```\n\n3. Deploy to testnet:\n   ```bash\n   ./scripts/deploy.sh\n   ```\n\n4. Query contract:\n   ```bash\n   ./scripts/query.sh --endpoint getSum\n   ./scripts/query.sh --endpoint getValue --arg myKey\n   ```\n\n5. Upgrade contract:\n   ```bash\n   ./scripts/upgrade.sh\n   ```\n\nAll deployment history is tracked in `output/history.json` for easy reference.\n\n## Automatic Context Enhancement\n\nThe MCP server can automatically enhance queries with relevant Klever VM context. This ensures your MCP client always has access to the most relevant information.\n\n### Using Context Enhancement\n\nUse the `enhance_with_context` tool to automatically add relevant context to any query:\n\n```json\n{\n  \"tool\": \"enhance_with_context\",\n  \"arguments\": {\n    \"query\": \"How do I create a storage mapper?\",\n    \"autoInclude\": true\n  }\n}\n```\n\nThis will:\n1. Extract relevant keywords from the query\n2. Search the knowledge base for matching contexts\n3. Return an enhanced query with context included\n4. Provide metadata about what was found\n\n### Integration Pattern\n\nFor MCP clients that want to always check Klever context first:\n\n```javascript\n// Always enhance Klever-related queries\nif (query.match(/klever|kvm|smart contract|endpoint/i)) {\n  const enhanced = await callTool('enhance_with_context', { query });\n  // Use enhanced.enhancedQuery for processing\n}\n```\n\nThe context enhancement feature automatically enriches queries with relevant Klever VM knowledge from the comprehensive knowledge base.\n\n## Integration Examples\n\n### VS Code Extension\n```typescript\n// Query for token transfer examples\nconst response = await fetch('http://localhost:3000/api/context/query', {\n  method: 'POST',\n  headers: { 'Content-Type': 'application/json' },\n  body: JSON.stringify({\n    query: 'transfer',\n    types: ['code_example'],\n    contractType: 'token'\n  })\n});\n```\n\n### CLI Tool\n```bash\n# Using curl to add context\ncurl -X POST http://localhost:3000/api/context \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"type\": \"security_tip\",\n    \"content\": \"Always check for zero address\",\n    \"metadata\": {\n      \"title\": \"Zero Address Check\",\n      \"tags\": [\"security\", \"validation\"]\n    }\n  }'\n```\n\n## Contributing\n\nContributions are welcome! Please:\n1. Fork the repository\n2. Create a feature branch\n3. Make your changes\n4. Add tests\n5. Submit a pull request\n\n## License\n\nMIT License - see LICENSE file for details\n\n## Acknowledgments\n\n- Inspired by [Context7 by Upstash](https://github.com/upstash/context7)\n- Built for the [Klever Blockchain](https://klever.io)\n- Uses the [Klever VM SDK (Rust)](https://github.com/klever-io/klever-vm-sdk-rs)",
  "bytes": 17789,
  "sha": "855b94a67113c1026f8d1331790ad18001cfeca4c0680b7611b8e26277d9ccf8",
  "repo_slug": "klever-io/mcp-klever-vm",
  "fonte": "repo",
  "truncated": false,
  "api": "https://agentalog.com/api/listings/mcp_io_github_klever_io_mcp_klever_vm_34d27345/readme"
}