npm package: @polymerdao/mcp-polymer
Description: A Model Context Protocol (MCP) server for blockchain event verification using Polymer's Prove API.
Author: Polymer Labs
Latest version: 0.3.0

# MCP Polymer Server

A Model Context Protocol (MCP) server that enables AI agents to interact with blockchain data through Polymer's proof API. Provides verified blockchain event data, cross-chain execution capabilities, and Ethereum RPC access.

[![npm version](https://badge.fury.io/js/@polymerdao%2Fmcp-polymer.svg)](https://www.npmjs.com/package/@polymerdao/mcp-polymer)

## 🚀 Installation

```bash
# Install globally
npm install -g @polymerdao/mcp-polymer

# Or use without installing
npx @polymerdao/mcp-polymer
```

## 🎯 Quick Start

### Claude Desktop Integration

Add to your Claude Desktop configuration (`~/Library/Application Support/Claude/claude_desktop_config.json`):

```json
{
  "mcpServers": {
    "mcp-polymer-mainnet": {
      "command": "npx",
      "args": ["@polymerdao/mcp-polymer", "--environment", "mainnet"],
      "env": {
        "POLYMER_API_KEY": "<your-mainnet-api-key>"
      }
    },
    "mcp-polymer-testnet": {
      "command": "npx", 
      "args": ["@polymerdao/mcp-polymer", "--environment", "testnet"],
      "env": {
        "POLYMER_API_KEY": "<your-testnet-api-key>"
      }
    }
  }
}
```

### Claude Code Integration

```bash
claude mcp add mcp-polymer-mainnet -e POLYMER_API_KEY=<your-key> -- npx @polymerdao/mcp-polymer --environment mainnet
claude mcp add mcp-polymer-testnet -e POLYMER_API_KEY=<your-key> -- npx @polymerdao/mcp-polymer --environment testnet
```

### Manual Usage

```bash
# Set API key
export POLYMER_API_KEY=your_api_key_here

# Start the server on mainnet
mcp-polymer --environment mainnet

# Start on different environments  
mcp-polymer --environment devnet
mcp-polymer --environment testnet
mcp-polymer --environment shadownet

# Get version
mcp-polymer --version
```

## 🛠️ Available Tools

The MCP server provides the following tools for AI agents:

### Polymer API Tools

| Tool | Description |
|------|-------------|
| `mcp_info_getClientUpdates` | Get client synchronization status across all chains |
| `mcp_info_getConnectedChains` | Retrieve real-time chain connection status |
| `mcp_proof_request` | Initiate a Polymer proof request for a blockchain event |
| `mcp_proof_queryJob` | Check the status of a proof generation job |
| `mcp_proof_query` | Query proof with additional filters |
| `mcp_proof_queryWithFilter` | Advanced proof querying with custom filters |
| `mcp_proof_queryJobStats` | Get statistics about proof jobs |
| `mcp_execute_request` | Submit cross-chain execution requests |
| `mcp_execute_query` | Query execution job status |
| `mcp_execute_queryWithFilter` | Query executions with filters |

### Ethereum RPC Tools

Dynamic tools for standard Ethereum JSON-RPC methods on supported chains:

| Tool Pattern | Description | Example |
|--------------|-------------|---------|
| `mcp_eth_getBlockByNumber` | Get block data by number | Get latest Ethereum block |
| `mcp_eth_getBlockByHash` | Get block data by hash | Get specific block |
| `mcp_eth_getLogs` | Retrieve event logs | Get contract events |
| `mcp_eth_getTransactionByHash` | Get transaction details | Transaction lookup |
| `mcp_eth_call` | Execute read-only contract call | Query contract state |

### Introspection Tools

| Tool | Description |
|------|-------------|
| `mcp_list_all_tools` | Get comprehensive list of all available tools |
| `mcp_get_tool_details` | Get detailed information about any tool |
| `mcp_get_chain_rpcs` | Retrieve available RPC endpoints for a chain |
| `mcp_get_chainlist_cache_stats` | Get chainlist cache statistics |
| `mcp_clear_chainlist_cache` | Clear the chainlist cache |

## ⚙️ Configuration

### Environment Variables

- `POLYMER_API_KEY` - Your Polymer API key (required)
- `POLYMER_ENVIRONMENT` - Environment selection (alternative to --environment)

### Command Line Arguments

```bash
mcp-polymer [options]

Options:
  --environment <env>    Environment: devnet|testnet|shadownet|mainnet (default: mainnet)
  --version, -v         Show version number
  --help               Show help
```

### Environment Configurations

| Environment | Description | Use Case |
|-------------|-------------|----------|
| `mainnet` | Production Polymer network | Live applications, production AI agents |
| `testnet` | Test network | Development, testing |
| `shadownet` | Shadow/staging network | Pre-production testing |
| `devnet` | Development network | Early development |

## 🔧 Development

### Building from Source

```bash
# Clone the monorepo
git clone https://github.com/polymerdao/mcp-polymer.git
cd mcp-polymer/packages/mcp-server

# Install dependencies
npm install

# Build
npm run build

# Run locally
node dist/main.js --environment mainnet
```

### Testing

```bash
# Run tests
npm test

# Run tests in watch mode  
npm run test:watch

# Run with coverage
npm run test:coverage
```

### MCP Testing with Inspector

Use the [MCP Inspector](https://github.com/modelcontextprotocol/mcp-inspector) to test the server:

```bash
# Install inspector
npm install -g @modelcontextprotocol/inspector

# Test the server
export POLYMER_API_KEY=your_api_key
npx @modelcontextprotocol/inspector npx @polymerdao/mcp-polymer --environment testnet
```

## 🏗️ Architecture

### Project Structure

```
src/
├── main.ts                   # Server entry point and CLI
├── config.ts                 # Environment and configuration management
├── types.ts                  # TypeScript type definitions
├── dynamic-tools.ts          # Dynamic tool registration from OpenRPC
├── ethereum-tools.ts         # Ethereum RPC tool management  
├── generated-tools.ts        # Auto-generated Polymer API tools
└── openrpc.ts               # OpenRPC specification handling
```

### Tool Registration

The server uses multiple registration strategies:

1. **Static Generated Tools**: Auto-generated from Polymer's OpenRPC specification
2. **Dynamic Ethereum Tools**: Generated from chainlist data for supported chains
3. **Manual Fallback Tools**: Hardcoded tools if generation fails
4. **Introspection Tools**: Built-in tools for discoverability

### Data Flow

```
AI Agent → MCP Client → MCP Server → Polymer API / Ethereum RPC → Blockchain
                                 ↓
                            Proof Verification
                                 ↓  
                         Verified Response → AI Agent
```

## 📊 Monitoring & Debugging

### Logging

The server outputs logs to stderr for debugging:

```bash
# Start with verbose logging
DEBUG=* mcp-polymer --environment testnet

# Server startup logs
MCP server started via stdio
Registered static MCP tools from Polymer OpenRPC spec
Dynamically registered 50+ Ethereum RPC tools
```

### Health Checks

```bash
# Test server is responding
echo '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}' | mcp-polymer --environment testnet
```

### Performance

- **Tool Caching**: Ethereum tools are cached for performance
- **Connection Pooling**: HTTP connections are reused
- **RPC Optimization**: Chainlist data is cached with smart invalidation

## 🔒 Security

### API Key Management

- API keys are never logged or exposed
- Keys are validated before first use
- Environment variables are preferred over CLI arguments

### Proof Verification

- Cryptographic signatures are verified locally
- ECDSA signature recovery and validation
- Merkle tree proof verification

### Error Handling

- Graceful degradation when services are unavailable
- Input validation on all parameters
- Safe JSON parsing and error reporting

## 📚 Examples

### Using with Claude

**Ask for blockchain data:**
> "Can you check the latest block on Ethereum mainnet?"

**Request a proof:**
> "Please request a proof for Ethereum event at global log index 12345, block 19000000"

**Cross-chain execution:**
> "I need to execute a cross-chain transaction. Here's my execution envelope: [JSON data]"

### Manual API Calls

```bash
# List all available tools
echo '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}' | mcp-polymer

# Get Ethereum block
echo '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"mcp_eth_getBlockByNumber","arguments":{"chain_name":"ethereum","block_number":"latest","include_transactions":false}}}' | mcp-polymer
```

## 🤝 Contributing

See the [main repository README](../../README.md) for contribution guidelines.

### Adding New Tools

1. Add tool definition to `src/generated-tools.ts` or `src/ethereum-tools.ts`
2. Implement the tool handler
3. Add tests in `tests/`
4. Update this README

### Environment Setup

```bash
# Development environment
export POLYMER_API_KEY=dev_key
export POLYMER_ENVIRONMENT=testnet

# Run in development mode
npm run build && node dist/main.js
```

## 📄 License

Apache 2.0 License - see [LICENSE](../../LICENSE) for details.

## 🔗 Related

- [Model Context Protocol Specification](https://modelcontextprotocol.io/specification)
- [Claude Desktop MCP Guide](https://claude.ai/mcp)
- [Polymer Labs Documentation](https://polymerlabs.org)