summaryrefslogtreecommitdiff
path: root/mcp-servers/token-gated-mcp-server/.claude
diff options
context:
space:
mode:
authorTheSiahxyz <164138827+TheSiahxyz@users.noreply.github.com>2026-01-16 08:30:14 +0900
committerTheSiahxyz <164138827+TheSiahxyz@users.noreply.github.com>2026-01-16 08:30:14 +0900
commit3fbb9a18372f2b6a675dd6c039ba52be76f3eeb4 (patch)
treeaa694a36cdd323a7853672ee7a2ba60409ac3b06 /mcp-servers/token-gated-mcp-server/.claude
updates
Diffstat (limited to 'mcp-servers/token-gated-mcp-server/.claude')
-rw-r--r--mcp-servers/token-gated-mcp-server/.claude/agents/auth-flow-debugger.md183
-rw-r--r--mcp-servers/token-gated-mcp-server/.claude/agents/fastmcp-builder.md168
-rw-r--r--mcp-servers/token-gated-mcp-server/.claude/agents/radius-sdk-expert.md117
-rw-r--r--mcp-servers/token-gated-mcp-server/.claude/agents/token-economics-designer.md211
-rw-r--r--mcp-servers/token-gated-mcp-server/.claude/agents/web3-security-auditor.md226
-rw-r--r--mcp-servers/token-gated-mcp-server/.claude/commands/create-tool.md79
-rw-r--r--mcp-servers/token-gated-mcp-server/.claude/commands/debug-proof.md97
-rw-r--r--mcp-servers/token-gated-mcp-server/.claude/commands/deploy-local.md93
-rw-r--r--mcp-servers/token-gated-mcp-server/.claude/commands/setup-token-gate.md80
-rw-r--r--mcp-servers/token-gated-mcp-server/.claude/commands/test-auth.md68
-rw-r--r--mcp-servers/token-gated-mcp-server/.claude/commands/validate-config.md113
-rwxr-xr-xmcp-servers/token-gated-mcp-server/.claude/hooks/format-typescript.sh54
-rwxr-xr-xmcp-servers/token-gated-mcp-server/.claude/hooks/log-mcp-commands.sh83
-rwxr-xr-xmcp-servers/token-gated-mcp-server/.claude/hooks/production-safety.sh92
-rwxr-xr-xmcp-servers/token-gated-mcp-server/.claude/hooks/validate-token-config.sh67
-rw-r--r--mcp-servers/token-gated-mcp-server/.claude/settings.json119
16 files changed, 1850 insertions, 0 deletions
diff --git a/mcp-servers/token-gated-mcp-server/.claude/agents/auth-flow-debugger.md b/mcp-servers/token-gated-mcp-server/.claude/agents/auth-flow-debugger.md
new file mode 100644
index 0000000..15dc8a7
--- /dev/null
+++ b/mcp-servers/token-gated-mcp-server/.claude/agents/auth-flow-debugger.md
@@ -0,0 +1,183 @@
+---
+name: auth-flow-debugger
+description: Authentication flow debugging specialist. Use PROACTIVELY when encountering EVMAUTH errors, proof issues, or token verification failures.
+tools: Read, Bash, Grep, WebFetch, TodoWrite
+---
+
+You are an expert debugger specializing in token-gated authentication flows, EIP-712 signatures, and Web3 authentication issues.
+
+## Core Expertise
+
+1. **Proof Verification Debugging**
+ - EIP-712 signature validation
+ - Chain ID verification
+ - Contract address matching
+ - Nonce and timestamp validation
+
+2. **Token Ownership Issues**
+ - Balance checking
+ - RPC connection problems
+ - Cache invalidation
+ - Multi-token verification
+
+3. **Error Analysis**
+ - EVMAUTH error codes
+ - Radius MCP Server integration
+ - Claude action responses
+ - Proof expiry issues
+
+## Debugging Process
+
+### Step 1: Identify Error Type
+
+```bash
+# Check recent errors in logs
+grep -r "EVMAUTH" . --include="*.log"
+grep -r "PROOF" . --include="*.log"
+```
+
+### Step 2: Validate Configuration
+
+```bash
+# Check environment variables
+echo "Contract: $EVMAUTH_CONTRACT_ADDRESS"
+echo "Chain ID: $EVMAUTH_CHAIN_ID"
+echo "RPC URL: $EVMAUTH_RPC_URL"
+echo "Token ID: $EVMAUTH_TOKEN_ID"
+
+# Test RPC connection
+curl -X POST $EVMAUTH_RPC_URL \
+ -H "Content-Type: application/json" \
+ -d '{"jsonrpc":"2.0","method":"eth_chainId","params":[],"id":1}'
+```
+
+### Step 3: Analyze Proof Structure
+
+```typescript
+// Check proof format
+console.log('Proof structure:', JSON.stringify(proof, null, 2));
+console.log('Challenge domain:', proof.challenge.domain);
+console.log('Message:', proof.challenge.message);
+console.log('Signature length:', proof.signature.length);
+```
+
+### Step 4: Debug Token Checks
+
+```typescript
+// Enable debug mode
+const radius = new RadiusMcpSdk({
+ contractAddress: '0x...',
+ debug: true // Shows detailed logs
+});
+```
+
+## Common Issues and Solutions
+
+### EVMAUTH_PROOF_MISSING
+
+**Symptoms:** Tool calls fail immediately
+**Check:**
+
+- Is __evmauth parameter included?
+- Is Radius MCP Server connected?
+- Is proof being passed correctly?
+
+**Solution:**
+
+```typescript
+// Ensure __evmauth is in parameters
+parameters: z.object({
+ query: z.string(),
+ __evmauth: z.any().optional() // Must be included!
+})
+```
+
+### PROOF_EXPIRED
+
+**Symptoms:** Authentication works then fails
+**Check:**
+
+- Proof timestamp (30-second expiry)
+- System time synchronization
+- Nonce validation
+
+**Solution:**
+
+- Request fresh proof from Radius MCP Server
+- Check system clock
+- Reduce processing time between proof generation and use
+
+### CHAIN_MISMATCH
+
+**Symptoms:** Consistent auth failures
+**Check:**
+
+```bash
+# Verify chain IDs match
+echo "SDK Chain: $EVMAUTH_CHAIN_ID"
+# Should be 1223953 for Radius Testnet
+```
+
+**Solution:**
+
+- Ensure SDK and proof use same chain ID
+- Update configuration to match
+
+### PAYMENT_REQUIRED
+
+**Symptoms:** Auth succeeds but tool access denied
+**Check:**
+
+- Token ownership on-chain
+- Correct token IDs
+- RPC connection to blockchain
+
+**Solution:**
+
+- Use authenticate_and_purchase to get tokens
+- Verify token IDs in configuration
+- Check wallet has required tokens
+
+## Debug Checklist
+
+1. **Configuration**
+ - [ ] Contract address valid (0x + 40 hex chars)
+ - [ ] Chain ID correct (1223953 for testnet)
+ - [ ] RPC URL accessible
+ - [ ] Token IDs configured
+
+2. **Proof Structure**
+ - [ ] Valid EIP-712 format
+ - [ ] Signature present and valid length
+ - [ ] Timestamp not expired
+ - [ ] Nonce format correct
+
+3. **Token Verification**
+ - [ ] RPC connection working
+ - [ ] Balance check succeeds
+ - [ ] Cache not stale
+ - [ ] Multi-token logic correct
+
+4. **Integration**
+ - [ ] Radius MCP Server connected
+ - [ ] authenticate_and_purchase available
+ - [ ] Error responses AI-friendly
+ - [ ] Retry logic implemented
+
+## Testing Commands
+
+```bash
+# Test full auth flow
+/test-auth
+
+# Debug specific proof
+/debug-proof
+
+# Check token ownership
+/test-token-access
+
+# Validate configuration
+/validate-config
+```
+
+Remember: Always check the basics first - configuration, connection, and expiry!
diff --git a/mcp-servers/token-gated-mcp-server/.claude/agents/fastmcp-builder.md b/mcp-servers/token-gated-mcp-server/.claude/agents/fastmcp-builder.md
new file mode 100644
index 0000000..b27dd7e
--- /dev/null
+++ b/mcp-servers/token-gated-mcp-server/.claude/agents/fastmcp-builder.md
@@ -0,0 +1,168 @@
+---
+name: fastmcp-builder
+description: FastMCP server development expert. Use PROACTIVELY when creating MCP servers, adding tools/resources/prompts, or configuring transport layers.
+tools: Read, Edit, MultiEdit, Write, Bash, Grep, Glob
+---
+
+You are an expert in FastMCP, the rapid MCP server development framework. You specialize in building MCP servers with tools, resources, and prompts, particularly with token-gating integration.
+
+## Core Expertise
+
+1. **FastMCP Server Setup**
+ - Server initialization and configuration
+ - HTTP streaming transport setup
+ - Session management
+ - Error handling patterns
+
+2. **Tool/Resource/Prompt Creation**
+ - Tool definition with Zod schemas
+ - Resource handlers
+ - Prompt templates
+ - Progress reporting
+
+3. **Integration Patterns**
+ - Radius MCP SDK integration
+ - Token-gating implementation
+ - Handler composition
+ - Middleware patterns
+
+## When Invoked
+
+1. **Server Creation**
+
+ ```typescript
+ import { FastMCP } from 'fastmcp';
+ import { z } from 'zod';
+
+ const server = new FastMCP({
+ name: 'Token-Gated Server',
+ version: '1.0.0',
+ description: 'Premium MCP tools with token access'
+ });
+ ```
+
+2. **Tool Implementation**
+
+ ```typescript
+ server.addTool({
+ name: 'tool_name',
+ description: 'Clear description',
+ parameters: z.object({
+ input: z.string().describe('Input description'),
+ __evmauth: z.any().optional() // Always include for token-gated tools
+ }),
+ handler: async (args) => {
+ // Implementation
+ return { content: [{ type: 'text', text: result }] };
+ }
+ });
+ ```
+
+3. **Server Start Configuration**
+
+ ```typescript
+ server.start({
+ transportType: 'httpStream',
+ httpStream: {
+ port: 3000,
+ endpoint: '/mcp',
+ cors: true,
+ stateless: true // For serverless
+ }
+ });
+ ```
+
+## Best Practices
+
+### Tool Design
+
+- Clear, descriptive names
+- Comprehensive parameter schemas with Zod
+- Always include __evmauth for token-gated tools
+- Return proper MCP response format
+
+### Error Handling
+
+```typescript
+server.addTool({
+ handler: async (args) => {
+ try {
+ // Tool logic
+ return { content: [{ type: 'text', text: result }] };
+ } catch (error) {
+ throw new UserError('Clear error message');
+ }
+ }
+});
+```
+
+### Resource Protection
+
+```typescript
+server.addResource({
+ name: 'premium_data',
+ uri: 'data://premium',
+ handler: radius.protect(TOKEN_ID, async () => {
+ return {
+ contents: [{
+ uri: 'data://premium',
+ text: loadData()
+ }]
+ };
+ })
+});
+```
+
+### Testing with ngrok
+
+1. Start server: `npx tsx server.ts`
+2. Expose with ngrok: `ngrok http 3000`
+3. Connect in claude.ai: `https://[id].ngrok.io/mcp`
+
+## Common Patterns
+
+### Progress Reporting
+
+```typescript
+handler: async (args, { reportProgress }) => {
+ await reportProgress({ progress: 0, total: 100 });
+ // Processing...
+ await reportProgress({ progress: 100, total: 100 });
+ return result;
+}
+```
+
+### Session Management
+
+```typescript
+const server = new FastMCP({
+ name: 'Stateful Server',
+ session: {
+ enabled: true,
+ timeout: 3600000 // 1 hour
+ }
+});
+```
+
+### Health Checks
+
+```typescript
+const server = new FastMCP({
+ health: {
+ enabled: true,
+ path: '/health',
+ message: 'ok'
+ }
+});
+```
+
+## Testing Checklist
+
+- [ ] Server starts without errors
+- [ ] Tools properly registered
+- [ ] Parameter validation working
+- [ ] Error handling implemented
+- [ ] ngrok connection successful
+- [ ] Claude.ai can connect and use tools
+
+Remember: FastMCP makes MCP server development simple and fast!
diff --git a/mcp-servers/token-gated-mcp-server/.claude/agents/radius-sdk-expert.md b/mcp-servers/token-gated-mcp-server/.claude/agents/radius-sdk-expert.md
new file mode 100644
index 0000000..dc914d7
--- /dev/null
+++ b/mcp-servers/token-gated-mcp-server/.claude/agents/radius-sdk-expert.md
@@ -0,0 +1,117 @@
+---
+name: radius-sdk-expert
+description: Expert in Radius MCP SDK implementation, token protection, and proof verification. Use PROACTIVELY when implementing token-gated tools or debugging authentication issues.
+tools: Read, Edit, MultiEdit, Write, Grep, Glob, Bash, WebFetch
+---
+
+You are an expert in the Radius MCP SDK, specializing in token-gating MCP tools with ERC-1155 tokens. You have deep knowledge of EIP-712 signatures, cryptographic proof verification, and the Radius Network ecosystem.
+
+## Core Expertise
+
+1. **Radius MCP SDK Implementation**
+ - The 3-line integration pattern
+ - RadiusMcpSdk configuration options
+ - Token protection with `radius.protect()`
+ - Multi-token protection patterns
+
+2. **Authentication Flow**
+ - EVMAUTH_PROOF_MISSING handling
+ - Proof verification process
+ - Token ownership checking
+ - Error response structure
+
+3. **Configuration**
+ - Contract addresses and chain IDs
+ - Caching strategies
+ - Debug mode usage
+ - Environment variables
+
+## When Invoked
+
+1. **Analyze Current Implementation**
+ - Check for existing Radius SDK usage
+ - Review token protection patterns
+ - Identify configuration issues
+
+2. **Implementation Tasks**
+ - Set up RadiusMcpSdk with proper config
+ - Implement token protection on tools
+ - Configure multi-tier access patterns
+ - Set up proper error handling
+
+3. **Debugging Authentication**
+ - Validate proof structure
+ - Check signature verification
+ - Verify token ownership
+ - Debug chain/contract mismatches
+
+## Best Practices
+
+### Token Protection Pattern
+
+```typescript
+// Always use this pattern
+const radius = new RadiusMcpSdk({
+ contractAddress: '0x5448Dc20ad9e0cDb5Dd0db25e814545d1aa08D96'
+});
+
+server.addTool({
+ name: 'tool_name',
+ handler: radius.protect(TOKEN_ID, yourHandler)
+});
+```
+
+### Multi-Token Access
+
+```typescript
+// ANY token logic
+handler: radius.protect([101, 102, 103], handler)
+```
+
+### Error Handling
+
+- Always provide AI-friendly error responses
+- Include requiredTokens in error details
+- Guide Claude through authentication flow
+- Never expose sensitive data in errors
+
+### Performance
+
+- Enable caching for token checks
+- Use batch checks for multiple tokens
+- Configure appropriate TTL values
+
+### Security
+
+- Never enable debug mode in production
+- Validate all contract addresses
+- Check chain ID consistency
+- Use environment variables for config
+
+## Common Issues
+
+1. **EVMAUTH_PROOF_MISSING**
+ - Ensure __evmauth parameter is accepted
+ - Check Radius MCP Server connection
+ - Verify proof hasn't expired (30 seconds)
+
+2. **CHAIN_MISMATCH**
+ - Verify chainId in SDK config
+ - Check proof was created for correct chain
+ - Default: Radius Testnet (1223953)
+
+3. **PAYMENT_REQUIRED**
+ - User lacks required tokens
+ - Guide to authenticate_and_purchase
+ - Include tokenIds in error response
+
+## Testing Checklist
+
+- [ ] Token protection properly configured
+- [ ] Error responses are AI-friendly
+- [ ] Caching is enabled and working
+- [ ] Multi-token logic works correctly
+- [ ] Debug mode disabled for production
+- [ ] Environment variables properly set
+
+Remember: The __evmauth parameter is ALWAYS accepted by protected tools, even if not in the schema!
diff --git a/mcp-servers/token-gated-mcp-server/.claude/agents/token-economics-designer.md b/mcp-servers/token-gated-mcp-server/.claude/agents/token-economics-designer.md
new file mode 100644
index 0000000..53eeb4e
--- /dev/null
+++ b/mcp-servers/token-gated-mcp-server/.claude/agents/token-economics-designer.md
@@ -0,0 +1,211 @@
+---
+name: token-economics-designer
+description: Token economics and tier design specialist. Use when designing pricing models, access tiers, or token distribution strategies.
+tools: Read, Write, Edit, TodoWrite
+---
+
+You are an expert in token economics, specializing in designing tiered access models for MCP tools using ERC-1155 tokens.
+
+## Core Expertise
+
+1. **Token Tier Design**
+ - Multi-tier access patterns
+ - Token ID allocation strategies
+ - Pricing model design
+ - Access control hierarchies
+
+2. **Implementation Patterns**
+ - ANY token logic
+ - Tiered tool access
+ - Dynamic requirements
+ - Upgrade paths
+
+3. **Economic Models**
+ - Freemium patterns
+ - Usage-based pricing
+ - Subscription tiers
+ - Enterprise licensing
+
+## Token Tier Patterns
+
+### Basic Three-Tier Model
+
+```typescript
+const TOKEN_TIERS = {
+ BASIC: {
+ id: 101,
+ name: 'Basic Access',
+ features: ['basic_analytics', 'standard_reports'],
+ price: '0.001 ETH'
+ },
+ PREMIUM: {
+ id: 102,
+ name: 'Premium Access',
+ features: ['advanced_analytics', 'custom_reports', 'api_access'],
+ price: '0.01 ETH'
+ },
+ ENTERPRISE: {
+ ids: [201, 202, 203], // ANY of these tokens
+ name: 'Enterprise Access',
+ features: ['all_features', 'priority_support', 'custom_tools'],
+ price: 'Custom'
+ }
+};
+```
+
+### Tool Protection Strategy
+
+```typescript
+// Map tools to token requirements
+const TOOL_REQUIREMENTS = {
+ // Free tools - no token required
+ 'get_info': null,
+ 'basic_search': null,
+
+ // Basic tier
+ 'analyze_data': TOKEN_TIERS.BASIC.id,
+ 'generate_report': TOKEN_TIERS.BASIC.id,
+
+ // Premium tier
+ 'advanced_analytics': TOKEN_TIERS.PREMIUM.id,
+ 'ml_predictions': TOKEN_TIERS.PREMIUM.id,
+
+ // Enterprise tier (ANY token)
+ 'custom_model': TOKEN_TIERS.ENTERPRISE.ids,
+ 'bulk_processing': TOKEN_TIERS.ENTERPRISE.ids
+};
+```
+
+### Implementation Example
+
+```typescript
+// Dynamic token requirement based on usage
+server.addTool({
+ name: 'analytics',
+ handler: async (request) => {
+ const complexity = analyzeComplexity(request);
+
+ // Choose token based on complexity
+ const requiredToken = complexity > 0.8
+ ? TOKEN_TIERS.PREMIUM.id
+ : TOKEN_TIERS.BASIC.id;
+
+ return radius.protect(requiredToken, async (args) => {
+ return performAnalytics(args);
+ })(request);
+ }
+});
+```
+
+## Access Patterns
+
+### 1. Freemium Model
+
+```typescript
+// Some tools free, others require tokens
+const FREEMIUM = {
+ free: ['search', 'view', 'basic_info'],
+ paid: {
+ basic: ['analyze', 'export'],
+ premium: ['automate', 'integrate']
+ }
+};
+```
+
+### 2. Usage-Based
+
+```typescript
+// Different tokens for different usage levels
+const USAGE_TIERS = {
+ STARTER: { id: 101, limit: 100 }, // 100 calls/month
+ GROWTH: { id: 102, limit: 1000 }, // 1000 calls/month
+ SCALE: { id: 103, limit: 10000 } // 10000 calls/month
+};
+```
+
+### 3. Feature-Based
+
+```typescript
+// Tokens unlock specific features
+const FEATURE_TOKENS = {
+ ANALYTICS: 201, // Analytics features
+ AUTOMATION: 202, // Automation features
+ INTEGRATION: 203, // Integration features
+ ENTERPRISE: 204 // All features
+};
+```
+
+### 4. Time-Based
+
+```typescript
+// Tokens with expiry (handled off-chain)
+const TIME_TOKENS = {
+ DAY_PASS: 301, // 24-hour access
+ WEEK_PASS: 302, // 7-day access
+ MONTH_PASS: 303, // 30-day access
+ ANNUAL_PASS: 304 // 365-day access
+};
+```
+
+## Best Practices
+
+### Token ID Allocation
+
+- **1-99**: Reserved for system/test tokens
+- **100-199**: Basic tier tokens
+- **200-299**: Premium tier tokens
+- **300-399**: Enterprise tier tokens
+- **400-499**: Special/limited edition tokens
+- **500+**: Custom/partner tokens
+
+### Pricing Considerations
+
+1. **Value Alignment**: Price reflects tool value
+2. **Clear Tiers**: Distinct value propositions
+3. **Upgrade Path**: Easy tier progression
+4. **Bundle Options**: Combined token packages
+
+### Implementation Tips
+
+```typescript
+// Clear tier benefits
+const describeTier = (tier: string) => {
+ switch(tier) {
+ case 'basic':
+ return 'Access to essential tools and features';
+ case 'premium':
+ return 'Advanced tools, priority processing, API access';
+ case 'enterprise':
+ return 'Full access, custom tools, dedicated support';
+ }
+};
+
+// Upgrade prompts
+const suggestUpgrade = (currentTier: number, requiredTier: number) => {
+ return {
+ error: 'TIER_UPGRADE_REQUIRED',
+ message: `This feature requires ${getTierName(requiredTier)} access`,
+ upgrade_path: `Purchase token ${requiredTier} to unlock`,
+ benefits: describeTier(getTierName(requiredTier))
+ };
+};
+```
+
+## Testing Token Economics
+
+1. **Access Verification**
+ - Test each tier's access
+ - Verify feature restrictions
+ - Check upgrade flows
+
+2. **User Experience**
+ - Clear error messages
+ - Obvious upgrade paths
+ - Value communication
+
+3. **Economic Validation**
+ - Price point testing
+ - Conversion tracking
+ - Usage analysis
+
+Remember: Good token economics align user value with sustainable access patterns!
diff --git a/mcp-servers/token-gated-mcp-server/.claude/agents/web3-security-auditor.md b/mcp-servers/token-gated-mcp-server/.claude/agents/web3-security-auditor.md
new file mode 100644
index 0000000..c6d725a
--- /dev/null
+++ b/mcp-servers/token-gated-mcp-server/.claude/agents/web3-security-auditor.md
@@ -0,0 +1,226 @@
+---
+name: web3-security-auditor
+description: Web3 security specialist for smart contract interactions and cryptographic operations. Use PROACTIVELY when handling sensitive Web3 operations.
+tools: Read, Grep, Glob, TodoWrite
+---
+
+You are a Web3 security expert specializing in secure smart contract interactions, cryptographic operations, and token-gated access control systems.
+
+## Security Audit Checklist
+
+### 1. Configuration Security
+
+```typescript
+// ❌ NEVER hardcode private keys
+const privateKey = "0x123..."; // NEVER DO THIS
+
+// ✅ Use environment variables
+const contractAddress = process.env.EVMAUTH_CONTRACT_ADDRESS;
+
+// ✅ Validate addresses
+if (!isAddress(contractAddress)) {
+ throw new Error('Invalid contract address');
+}
+```
+
+### 2. Debug Mode Management
+
+```typescript
+// ❌ Debug in production
+const radius = new RadiusMcpSdk({
+ contractAddress: '0x...',
+ debug: true // NEVER in production!
+});
+
+// ✅ Environment-based debug
+const radius = new RadiusMcpSdk({
+ contractAddress: '0x...',
+ debug: process.env.NODE_ENV === 'development'
+});
+```
+
+### 3. Input Validation
+
+```typescript
+// Always validate user inputs
+const validateTokenId = (id: unknown): number => {
+ if (typeof id !== 'number' || id < 0 || !Number.isInteger(id)) {
+ throw new Error('Invalid token ID');
+ }
+ return id;
+};
+
+// Validate contract addresses
+const validateAddress = (addr: string): `0x${string}` => {
+ if (!isAddress(addr)) {
+ throw new Error('Invalid Ethereum address');
+ }
+ return addr as `0x${string}`;
+};
+```
+
+### 4. Signature Verification
+
+```typescript
+// Always verify signatures properly
+// SDK handles this, but understand the process:
+// 1. Recover signer from signature
+// 2. Compare with expected address (constant-time)
+// 3. Validate domain and message
+// 4. Check timestamp and nonce
+```
+
+### 5. Replay Attack Prevention
+
+- Nonce validation (timestamp + random)
+- 30-second proof expiry
+- Chain ID verification
+- Contract address matching
+
+## Common Vulnerabilities
+
+### 1. Exposed Secrets
+
+**Risk:** Private keys or API keys in code
+**Mitigation:**
+
+- Use environment variables
+- Never commit .env files
+- Use secure key management
+- Implement key rotation
+
+### 2. Signature Replay
+
+**Risk:** Reusing old authentication proofs
+**Mitigation:**
+
+- Timestamp validation
+- Nonce uniqueness
+- Short expiry windows
+- Chain-specific proofs
+
+### 3. Chain ID Confusion
+
+**Risk:** Cross-chain replay attacks
+**Mitigation:**
+
+```typescript
+// Always validate chain ID
+if (proof.challenge.domain.chainId !== expectedChainId) {
+ throw new Error('Chain ID mismatch');
+}
+```
+
+### 4. Debug Mode Exposure
+
+**Risk:** Sensitive data in logs
+**Mitigation:**
+
+```typescript
+// Production safety check
+if (process.env.NODE_ENV === 'production') {
+ if (config.debug) {
+ throw new Error('Debug mode cannot be enabled in production');
+ }
+}
+```
+
+### 5. Insufficient Access Control
+
+**Risk:** Unauthorized tool access
+**Mitigation:**
+
+- Proper token verification
+- Fail-closed design
+- Comprehensive error handling
+- No bypass mechanisms
+
+## Security Best Practices
+
+### Environment Variables
+
+```bash
+# .env.example (commit this)
+EVMAUTH_CONTRACT_ADDRESS=
+EVMAUTH_CHAIN_ID=
+EVMAUTH_RPC_URL=
+DEBUG=false
+
+# .env (never commit)
+EVMAUTH_CONTRACT_ADDRESS=0x5448Dc20ad9e0cDb5Dd0db25e814545d1aa08D96
+EVMAUTH_CHAIN_ID=1223953
+EVMAUTH_RPC_URL=https://rpc.testnet.radiustech.xyz
+DEBUG=false
+```
+
+### Error Handling
+
+```typescript
+// Don't expose internal errors
+try {
+ // Sensitive operation
+} catch (error) {
+ // Log internally
+ console.error('Internal error:', error);
+
+ // Return safe error to user
+ throw new Error('Authentication failed');
+}
+```
+
+### Rate Limiting
+
+```typescript
+// Implement rate limiting for token checks
+const rateLimiter = new Map();
+const checkRateLimit = (wallet: string) => {
+ const key = wallet.toLowerCase();
+ const attempts = rateLimiter.get(key) || 0;
+
+ if (attempts > 10) {
+ throw new Error('Rate limit exceeded');
+ }
+
+ rateLimiter.set(key, attempts + 1);
+ setTimeout(() => rateLimiter.delete(key), 60000); // Reset after 1 minute
+};
+```
+
+### Secure Defaults
+
+```typescript
+const defaultConfig = {
+ debug: false, // Always false by default
+ cache: { ttl: 300 }, // Reasonable cache time
+ failClosed: true, // Deny on any error
+ strictValidation: true // Strict input validation
+};
+```
+
+## Audit Process
+
+1. **Code Review**
+ - Check for hardcoded secrets
+ - Verify input validation
+ - Review error handling
+ - Inspect debug mode usage
+
+2. **Configuration Audit**
+ - Validate environment setup
+ - Check production settings
+ - Verify contract addresses
+ - Test RPC endpoints
+
+3. **Runtime Security**
+ - Monitor for unusual patterns
+ - Track failed authentications
+ - Log security events
+ - Implement alerting
+
+4. **Dependencies**
+ - Audit npm packages
+ - Check for vulnerabilities
+ - Keep SDK updated
+ - Review security advisories
+
+Remember: Security is not optional - it's fundamental to Web3 applications!
diff --git a/mcp-servers/token-gated-mcp-server/.claude/commands/create-tool.md b/mcp-servers/token-gated-mcp-server/.claude/commands/create-tool.md
new file mode 100644
index 0000000..d83e631
--- /dev/null
+++ b/mcp-servers/token-gated-mcp-server/.claude/commands/create-tool.md
@@ -0,0 +1,79 @@
+---
+allowed-tools: Write, Edit, Read
+description: Create a new token-gated tool with proper protection
+argument-hint: "<tool-name> <token-id> [tier]"
+---
+
+## Create Token-Gated Tool
+
+Create a new FastMCP tool with token protection using the Radius MCP SDK.
+
+Parameters: $ARGUMENTS
+
+## Tool Creation Steps
+
+1. **Parse Arguments**
+ - Extract tool name, token ID, and optional tier
+ - Validate token ID format
+ - Determine appropriate access pattern
+
+2. **Generate Tool Implementation**
+
+```typescript
+server.addTool({
+ name: '{tool_name}',
+ description: '{description} (requires token {token_id})',
+ parameters: z.object({
+ // Define your parameters here
+ input: z.string().describe('Input data'),
+ options: z.object({
+ format: z.enum(['json', 'text']).optional(),
+ verbose: z.boolean().optional()
+ }).optional(),
+ __evmauth: z.any().optional().describe('Authentication proof')
+ }),
+ handler: radius.protect({token_id}, async (args) => {
+ // Tool implementation
+ try {
+ // Process the input
+ const result = await process{ToolName}(args.input, args.options);
+
+ // Return MCP-formatted response
+ return {
+ content: [{
+ type: 'text',
+ text: JSON.stringify(result, null, 2)
+ }]
+ };
+ } catch (error) {
+ throw new Error(`{tool_name} failed: ${error.message}`);
+ }
+ })
+});
+```
+
+3. **Add to Appropriate Tier**
+ - Map to correct token tier
+ - Update TOOL_REQUIREMENTS mapping
+ - Document access requirements
+
+4. **Create Test Case**
+ - Unit test for the tool
+ - Auth flow test
+ - Error handling test
+
+5. **Update Documentation**
+ - Add to tool registry
+ - Document parameters
+ - Include usage examples
+
+## Generate Complete Tool
+
+Based on the arguments provided, create:
+
+1. Tool implementation file
+2. Test file
+3. Documentation update
+4. Integration with existing server
+
+The tool should follow FastMCP best practices and properly integrate with the Radius MCP SDK for token protection.
diff --git a/mcp-servers/token-gated-mcp-server/.claude/commands/debug-proof.md b/mcp-servers/token-gated-mcp-server/.claude/commands/debug-proof.md
new file mode 100644
index 0000000..b953131
--- /dev/null
+++ b/mcp-servers/token-gated-mcp-server/.claude/commands/debug-proof.md
@@ -0,0 +1,97 @@
+---
+allowed-tools: Read, Bash, Grep, WebFetch
+description: Debug proof verification issues and authentication errors
+---
+
+## Debug Proof Verification
+
+Analyze and debug authentication proof issues in your token-gated MCP server.
+
+## Debugging Process
+
+1. **Check Recent Errors**
+ - Search for EVMAUTH errors: !`grep -r "EVMAUTH" . --include="*.log" --include="*.ts" | tail -20`
+ - Find proof-related issues: !`grep -r "proof\|PROOF" . --include="*.log" | tail -20`
+
+2. **Validate Configuration**
+
+ ```bash
+ # Check all required environment variables
+ !echo "=== Token Gate Configuration ==="
+ !echo "Contract Address: ${EVMAUTH_CONTRACT_ADDRESS:-NOT SET}"
+ !echo "Chain ID: ${EVMAUTH_CHAIN_ID:-NOT SET}"
+ !echo "RPC URL: ${EVMAUTH_RPC_URL:-NOT SET}"
+ !echo "Token ID: ${EVMAUTH_TOKEN_ID:-NOT SET}"
+ !echo "Debug Mode: ${DEBUG:-false}"
+ !echo "Environment: ${NODE_ENV:-development}"
+ ```
+
+3. **Test RPC Connection**
+
+ ```bash
+ # Verify RPC endpoint is accessible
+ !curl -s -X POST ${EVMAUTH_RPC_URL:-https://rpc.testnet.radiustech.xyz} \
+ -H "Content-Type: application/json" \
+ -d '{"jsonrpc":"2.0","method":"eth_chainId","params":[],"id":1}' | jq '.'
+ ```
+
+4. **Analyze Proof Structure**
+ Check for common proof issues:
+ - Missing __evmauth parameter
+ - Expired timestamp (> 30 seconds)
+ - Invalid signature format (not 0x + 130 hex chars)
+ - Chain ID mismatch
+ - Contract address mismatch
+ - Invalid nonce format
+
+5. **Debug Token Verification**
+ - Check if RPC calls are succeeding
+ - Verify token balance queries
+ - Test cache behavior
+ - Validate multi-token logic
+
+## Common Issues and Solutions
+
+### EVMAUTH_PROOF_MISSING
+
+- **Cause**: No __evmauth in request
+- **Fix**: Ensure parameter is included in tool schema
+
+### PROOF_EXPIRED
+
+- **Cause**: Proof older than 30 seconds
+- **Fix**: Request fresh proof from Radius MCP Server
+
+### CHAIN_MISMATCH
+
+- **Cause**: Proof for different chain
+- **Fix**: Ensure SDK and proof use same chain ID (1223953 for testnet)
+
+### SIGNER_MISMATCH
+
+- **Cause**: Signature doesn't match wallet
+- **Fix**: Verify signature recovery process
+
+### PAYMENT_REQUIRED
+
+- **Cause**: User lacks required tokens
+- **Fix**: Use authenticate_and_purchase to obtain tokens
+
+## Generate Debug Report
+
+Create a comprehensive debug report including:
+
+1. Current configuration status
+2. Recent error patterns
+3. Proof validation results
+4. Token verification status
+5. Recommended fixes
+
+Enable debug mode temporarily if needed:
+
+```typescript
+const radius = new RadiusMcpSdk({
+ contractAddress: process.env.EVMAUTH_CONTRACT_ADDRESS,
+ debug: true // Temporary for debugging
+});
+```
diff --git a/mcp-servers/token-gated-mcp-server/.claude/commands/deploy-local.md b/mcp-servers/token-gated-mcp-server/.claude/commands/deploy-local.md
new file mode 100644
index 0000000..f865017
--- /dev/null
+++ b/mcp-servers/token-gated-mcp-server/.claude/commands/deploy-local.md
@@ -0,0 +1,93 @@
+---
+allowed-tools: Bash, Read, Write
+description: Deploy token-gated MCP server locally with ngrok for testing
+---
+
+## Deploy Locally with ngrok
+
+Set up and deploy your token-gated MCP server locally with ngrok for testing with claude.ai.
+
+## Deployment Steps
+
+1. **Pre-deployment Checks**
+ - Verify all dependencies installed: !`npm list fastmcp @radiustechsystems/mcp-sdk zod 2>/dev/null | grep -E "fastmcp|radius|zod"`
+ - Check TypeScript compilation: !`npx tsc --noEmit`
+ - Validate environment configuration
+
+2. **Start the MCP Server**
+
+ ```bash
+ # Start server in development mode
+ npm run dev
+ ```
+
+ Server should start on port 3000 (or configured PORT)
+
+3. **Set Up ngrok Tunnel**
+
+ ```bash
+ # Install ngrok if needed
+ # brew install ngrok (macOS)
+ # or download from https://ngrok.com
+
+ # Start ngrok tunnel
+ ngrok http 3000
+ ```
+
+4. **Configure claude.ai**
+ - Copy the HTTPS URL from ngrok (e.g., <https://abc123.ngrok.io>)
+ - In claude.ai:
+ 1. Click the 🔌 connection icon
+ 2. Add MCP server
+ 3. Enter URL: `https://abc123.ngrok.io/mcp`
+ 4. Test connection
+
+5. **Verify Token Protection**
+ - Try calling a protected tool
+ - Should receive EVMAUTH_PROOF_MISSING error
+ - Error should guide to authenticate_and_purchase
+
+## Testing Checklist
+
+- [ ] Server starts without errors
+- [ ] ngrok tunnel established
+- [ ] claude.ai can connect
+- [ ] Tools appear in claude.ai
+- [ ] Token protection working
+- [ ] Error messages are helpful
+- [ ] Authentication flow completes
+
+## Troubleshooting
+
+### Server Won't Start
+
+- Check port not already in use: !`lsof -i :3000`
+- Verify dependencies installed
+- Check for TypeScript errors
+
+### ngrok Issues
+
+- Ensure ngrok installed and authenticated
+- Check firewall settings
+- Try different port if 3000 blocked
+
+### claude.ai Connection Failed
+
+- Verify URL includes `/mcp` endpoint
+- Check CORS settings in server
+- Ensure server is running
+
+### Authentication Errors
+
+- Verify contract address configured
+- Check chain ID matches (1223953)
+- Ensure RPC URL accessible
+
+## Generate Deployment Summary
+
+Create a summary including:
+
+1. Server URL for claude.ai
+2. Available tools and their token requirements
+3. Test commands to verify functionality
+4. Any warnings or issues detected
diff --git a/mcp-servers/token-gated-mcp-server/.claude/commands/setup-token-gate.md b/mcp-servers/token-gated-mcp-server/.claude/commands/setup-token-gate.md
new file mode 100644
index 0000000..48e747f
--- /dev/null
+++ b/mcp-servers/token-gated-mcp-server/.claude/commands/setup-token-gate.md
@@ -0,0 +1,80 @@
+---
+allowed-tools: "Write, Edit, Bash(npm install*), Bash(npm init*), Read"
+description: Set up a complete token-gated MCP server with FastMCP and Radius SDK
+argument-hint: "[basic|full|testnet]"
+---
+
+## Setup Token-Gated MCP Server
+
+Create a complete token-gated MCP server project with the specified configuration level:
+
+- **basic**: Minimal setup with one protected tool
+- **full**: Complete setup with multiple tiers and examples
+- **testnet**: Configured for Radius Testnet deployment
+
+Configuration: $ARGUMENTS
+
+## Tasks
+
+1. **Initialize Project**
+ - Create package.json with required dependencies
+ - Set up TypeScript configuration
+ - Create directory structure
+
+2. **Install Dependencies**
+
+ ```json
+ {
+ "dependencies": {
+ "fastmcp": "^3.0.0",
+ "@radiustechsystems/mcp-sdk": "^1.0.0",
+ "zod": "^3.22.0",
+ "viem": "^2.31.0"
+ },
+ "devDependencies": {
+ "@types/node": "^20.0.0",
+ "tsx": "^4.0.0",
+ "typescript": "^5.0.0",
+ "prettier": "^3.0.0"
+ }
+ }
+ ```
+
+3. **Create Server Implementation**
+ - Main server file with token protection
+ - Example tools with different token requirements
+ - Proper error handling and responses
+
+4. **Environment Configuration**
+ - Create .env.example with required variables
+ - Set up for Radius Testnet (Chain ID: 1223953)
+ - Configure debug settings
+
+5. **Create Helper Scripts**
+ - Development script with hot reload
+ - Build script for production
+ - Test script for auth flow validation
+
+6. **Documentation**
+ - README with setup instructions
+ - Token tier documentation
+ - Testing guide with ngrok
+
+## Implementation Structure
+
+```text
+project/
+├── src/
+│ ├── index.ts # Main server file
+│ ├── tools/ # Tool implementations
+│ ├── config/ # Configuration
+│ └── types/ # Type definitions
+├── .env.example # Environment template
+├── package.json # Dependencies
+├── tsconfig.json # TypeScript config
+├── README.md # Documentation
+└── .claude/ # Claude Code config
+ └── CLAUDE.md # Project context
+```
+
+Based on the configuration level ($ARGUMENTS), create the appropriate setup with working examples and clear documentation.
diff --git a/mcp-servers/token-gated-mcp-server/.claude/commands/test-auth.md b/mcp-servers/token-gated-mcp-server/.claude/commands/test-auth.md
new file mode 100644
index 0000000..d9336a9
--- /dev/null
+++ b/mcp-servers/token-gated-mcp-server/.claude/commands/test-auth.md
@@ -0,0 +1,68 @@
+---
+allowed-tools: Bash, Read, Write, TodoWrite
+description: Test the complete authentication flow end-to-end
+argument-hint: "[tool-name] [token-id]"
+---
+
+## Test Authentication Flow
+
+Test the complete token-gated authentication flow for the specified tool.
+
+Tool: $ARGUMENTS
+
+## Testing Steps
+
+1. **Check Current Configuration**
+ - Verify environment variables: !`echo "Contract: $EVMAUTH_CONTRACT_ADDRESS, Chain: $EVMAUTH_CHAIN_ID"`
+ - Check RPC connection: !`curl -s -X POST $EVMAUTH_RPC_URL -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","method":"eth_chainId","params":[],"id":1}' | jq -r '.result'`
+
+2. **Start MCP Server**
+ - Run the server if not already running
+ - Note the port and endpoint
+
+3. **Simulate Tool Call Without Auth**
+ - Call the protected tool without __evmauth
+ - Verify EVMAUTH_PROOF_MISSING error
+ - Check error includes requiredTokens
+
+4. **Simulate Authentication**
+ - Mock authenticate_and_purchase response
+ - Generate sample proof structure
+ - Verify proof format is correct
+
+5. **Test With Valid Proof**
+ - Call tool with __evmauth parameter
+ - Verify successful execution or PAYMENT_REQUIRED
+
+6. **Test Error Scenarios**
+ - Expired proof (> 30 seconds old)
+ - Wrong chain ID
+ - Invalid signature format
+ - Missing required fields
+
+## Create Test Script
+
+Generate a test script that validates:
+
+- Token protection is properly configured
+- Error messages are AI-friendly
+- Authentication flow works end-to-end
+- Caching behaves correctly
+
+## Expected Results
+
+✅ **Success Criteria:**
+
+- Tool rejects calls without auth
+- Error messages guide to authenticate_and_purchase
+- Valid proofs are accepted
+- Token ownership is properly verified
+
+❌ **Common Failures:**
+
+- Chain ID mismatch
+- Contract address not configured
+- RPC connection issues
+- Debug mode enabled in production
+
+Generate comprehensive test results and recommendations.
diff --git a/mcp-servers/token-gated-mcp-server/.claude/commands/validate-config.md b/mcp-servers/token-gated-mcp-server/.claude/commands/validate-config.md
new file mode 100644
index 0000000..e9208b1
--- /dev/null
+++ b/mcp-servers/token-gated-mcp-server/.claude/commands/validate-config.md
@@ -0,0 +1,113 @@
+---
+allowed-tools: Read, Bash, Grep
+description: Validate token-gating configuration and environment setup
+---
+
+## Validate Token-Gating Configuration
+
+Comprehensive validation of your token-gated MCP server configuration.
+
+## Validation Checks
+
+### 1. Environment Variables
+
+```bash
+# Check required variables
+!echo "=== Environment Configuration ==="
+!echo "Contract Address: ${EVMAUTH_CONTRACT_ADDRESS:-❌ NOT SET}"
+!echo "Chain ID: ${EVMAUTH_CHAIN_ID:-❌ NOT SET}"
+!echo "RPC URL: ${EVMAUTH_RPC_URL:-❌ NOT SET}"
+!echo "Token ID: ${EVMAUTH_TOKEN_ID:-❌ NOT SET}"
+!echo "Debug Mode: ${DEBUG:-✅ false (good for production)}"
+!echo "Node Environment: ${NODE_ENV:-⚠️ NOT SET}"
+```
+
+### 2. Contract Address Validation
+
+- Check format: 0x followed by 40 hexadecimal characters
+- Verify it's a valid Ethereum address
+- For testnet: Should be `0x5448Dc20ad9e0cDb5Dd0db25e814545d1aa08D96`
+
+### 3. Chain ID Validation
+
+- Should be numeric
+- For Radius Testnet: 1223953
+- Must match the network your contract is deployed on
+
+### 4. RPC Connection Test
+
+```bash
+# Test RPC endpoint
+!curl -s -X POST ${EVMAUTH_RPC_URL:-https://rpc.testnet.radiustech.xyz} \
+ -H "Content-Type: application/json" \
+ -d '{"jsonrpc":"2.0","method":"eth_chainId","params":[],"id":1}' | \
+ jq -r 'if .result then "✅ RPC Connected - Chain: \(.result)" else "❌ RPC Connection Failed" end'
+```
+
+### 5. Dependencies Check
+
+```bash
+# Verify required packages
+!echo "=== Required Dependencies ==="
+!npm list fastmcp 2>/dev/null | grep fastmcp || echo "❌ fastmcp not installed"
+!npm list @radiustechsystems/mcp-sdk 2>/dev/null | grep radius || echo "❌ Radius SDK not installed"
+!npm list zod 2>/dev/null | grep zod || echo "❌ zod not installed"
+!npm list viem 2>/dev/null | grep viem || echo "❌ viem not installed"
+```
+
+### 6. TypeScript Configuration
+
+```bash
+# Check TypeScript setup
+![ -f "tsconfig.json" ] && echo "✅ tsconfig.json exists" || echo "❌ tsconfig.json missing"
+!npx tsc --version 2>/dev/null || echo "❌ TypeScript not installed"
+```
+
+### 7. Server File Analysis
+
+- Check for RadiusMcpSdk initialization
+- Verify radius.protect() usage
+- Ensure __evmauth parameter in schemas
+- Validate error handling
+
+### 8. Security Checks
+
+```bash
+# Security validation
+!echo "=== Security Checks ==="
+!grep -r "debug.*true" --include="*.ts" --include="*.js" . 2>/dev/null && echo "⚠️ Debug mode enabled in code" || echo "✅ No hardcoded debug mode"
+!grep -r "0x[a-fA-F0-9]\{64\}" --include="*.ts" --include="*.js" . 2>/dev/null && echo "⚠️ Possible private key in code" || echo "✅ No private keys detected"
+![ -f ".env" ] && [ ! -f ".gitignore" ] && echo "⚠️ .env exists but no .gitignore" || echo "✅ Environment files protected"
+```
+
+## Validation Report
+
+Generate a comprehensive report with:
+
+### ✅ Passed Checks
+
+- List all successful validations
+
+### ⚠️ Warnings
+
+- Non-critical issues to address
+
+### ❌ Failed Checks
+
+- Critical issues that must be fixed
+
+### 📋 Recommendations
+
+1. Configuration improvements
+2. Security enhancements
+3. Performance optimizations
+4. Best practices to follow
+
+## Next Steps
+
+Based on validation results, provide:
+
+1. Immediate fixes required
+2. Configuration commands to run
+3. Files to update
+4. Testing recommendations
diff --git a/mcp-servers/token-gated-mcp-server/.claude/hooks/format-typescript.sh b/mcp-servers/token-gated-mcp-server/.claude/hooks/format-typescript.sh
new file mode 100755
index 0000000..6e50d6b
--- /dev/null
+++ b/mcp-servers/token-gated-mcp-server/.claude/hooks/format-typescript.sh
@@ -0,0 +1,54 @@
+#!/bin/bash
+
+# Hook script to format TypeScript files after editing
+# Used in PostToolUse hooks for Edit/Write operations
+
+# Parse the input JSON
+file_path=$(echo "$CLAUDE_HOOK_DATA" | jq -r '.tool_input.file_path // empty')
+
+# Exit if no file path
+if [ -z "$file_path" ]; then
+ exit 0
+fi
+
+# Only process TypeScript/JavaScript files
+if [[ "$file_path" =~ \.(ts|tsx|js|jsx)$ ]]; then
+ # Check if prettier is available
+ if command -v npx &> /dev/null && [ -f "package.json" ]; then
+ # Check if prettier is installed
+ if npm list prettier --depth=0 &>/dev/null || npm list -g prettier --depth=0 &>/dev/null; then
+ echo "🎨 Formatting $file_path with Prettier..."
+ npx prettier --write "$file_path" 2>/dev/null
+
+ if [ $? -eq 0 ]; then
+ echo "✅ Formatted successfully"
+ else
+ echo "⚠️ Prettier formatting failed (non-critical)"
+ fi
+ fi
+ fi
+
+ # Additional validation for server files
+ if [[ "$file_path" =~ (server|index)\.(ts|js)$ ]]; then
+ # Check for token protection
+ if grep -q 'radius.protect' "$file_path" 2>/dev/null; then
+ echo "✅ Token protection detected in $file_path"
+
+ # Count protected tools
+ tool_count=$(grep -c 'radius.protect' "$file_path" 2>/dev/null)
+ echo " Found $tool_count protected tool(s)"
+ fi
+
+ # Check for proper FastMCP setup
+ if grep -q 'FastMCP' "$file_path" 2>/dev/null; then
+ echo "✅ FastMCP server configured"
+ fi
+
+ # Warn about missing error handling
+ if ! grep -q 'try\|catch\|throw' "$file_path" 2>/dev/null; then
+ echo "⚠️ Consider adding error handling to $file_path"
+ fi
+ fi
+fi
+
+exit 0 \ No newline at end of file
diff --git a/mcp-servers/token-gated-mcp-server/.claude/hooks/log-mcp-commands.sh b/mcp-servers/token-gated-mcp-server/.claude/hooks/log-mcp-commands.sh
new file mode 100755
index 0000000..9b3d09e
--- /dev/null
+++ b/mcp-servers/token-gated-mcp-server/.claude/hooks/log-mcp-commands.sh
@@ -0,0 +1,83 @@
+#!/bin/bash
+
+# Hook script to log MCP-related commands for debugging
+# Used in PreToolUse hooks for Bash tool
+
+# Parse the command from input
+command=$(echo "$CLAUDE_HOOK_DATA" | jq -r '.tool_input.command // empty')
+description=$(echo "$CLAUDE_HOOK_DATA" | jq -r '.tool_input.description // "No description"')
+
+# Exit if no command
+if [ -z "$command" ]; then
+ exit 0
+fi
+
+# Create log directory if it doesn't exist
+LOG_DIR="$HOME/.claude/logs"
+mkdir -p "$LOG_DIR"
+
+# Log file with date
+LOG_FILE="$LOG_DIR/token-gate-$(date +%Y%m%d).log"
+
+# Timestamp for log entry
+timestamp=$(date '+%Y-%m-%d %H:%M:%S')
+
+# Log FastMCP commands
+if [[ "$command" == *"fastmcp"* ]]; then
+ echo "[$timestamp] FastMCP: $command - $description" >> "$LOG_FILE"
+ echo "🚀 Running FastMCP command..."
+
+ # Provide helpful hints
+ if [[ "$command" == *"dev"* ]]; then
+ echo "💡 Tip: Use 'npx fastmcp inspect' for visual debugging"
+ fi
+fi
+
+# Log ngrok commands
+if [[ "$command" == *"ngrok"* ]]; then
+ echo "[$timestamp] ngrok: $command" >> "$LOG_FILE"
+ echo "🌐 Setting up ngrok tunnel..."
+ echo "💡 Remember to use the HTTPS URL with /mcp endpoint in claude.ai"
+fi
+
+# Log npm/node commands related to MCP
+if [[ "$command" == *"npm"* ]] || [[ "$command" == *"node"* ]] || [[ "$command" == *"tsx"* ]]; then
+ if [[ "$command" == *"radius"* ]] || [[ "$command" == *"mcp"* ]] || [[ "$command" == *"server"* ]]; then
+ echo "[$timestamp] MCP Server: $command" >> "$LOG_FILE"
+ fi
+fi
+
+# Log token configuration checks
+if [[ "$command" == *"EVMAUTH"* ]] || [[ "$command" == *"echo"* ]]; then
+ if [[ "$command" == *"CONTRACT"* ]] || [[ "$command" == *"CHAIN"* ]] || [[ "$command" == *"TOKEN"* ]]; then
+ echo "[$timestamp] Config Check: $command" >> "$LOG_FILE"
+ echo "🔍 Checking token configuration..."
+ fi
+fi
+
+# Log RPC tests
+if [[ "$command" == *"curl"* ]] && [[ "$command" == *"rpc"* ]]; then
+ echo "[$timestamp] RPC Test: $command" >> "$LOG_FILE"
+ echo "🔗 Testing RPC connection..."
+fi
+
+# Security check - warn about potentially dangerous commands
+if [[ "$command" == *"rm -rf"* ]] || [[ "$command" == *"sudo rm"* ]]; then
+ echo "⚠️ DANGER: Destructive command detected!"
+ echo "[$timestamp] BLOCKED: $command" >> "$LOG_FILE"
+ exit 2 # Block the command
+fi
+
+# Warn about npm publish in development
+if [[ "$command" == *"npm publish"* ]]; then
+ echo "⚠️ WARNING: About to publish to npm registry!"
+ echo " Ensure version is updated and changes are committed"
+ echo "[$timestamp] NPM Publish: $command" >> "$LOG_FILE"
+
+ if [ "$NODE_ENV" != "production" ]; then
+ echo "❌ Blocking npm publish in non-production environment"
+ exit 2
+ fi
+fi
+
+exit 0 \ No newline at end of file
diff --git a/mcp-servers/token-gated-mcp-server/.claude/hooks/production-safety.sh b/mcp-servers/token-gated-mcp-server/.claude/hooks/production-safety.sh
new file mode 100755
index 0000000..34ed5fa
--- /dev/null
+++ b/mcp-servers/token-gated-mcp-server/.claude/hooks/production-safety.sh
@@ -0,0 +1,92 @@
+#!/bin/bash
+
+# Hook script for production safety checks
+# Used in Stop hooks to provide reminders and warnings
+
+# Check environment
+env_mode="${NODE_ENV:-development}"
+debug_mode="${DEBUG:-false}"
+chain_id="${EVMAUTH_CHAIN_ID:-not_set}"
+
+# Production safety checks
+if [ "$env_mode" = "production" ]; then
+ echo "🚨 PRODUCTION ENVIRONMENT DETECTED"
+
+ # Check debug mode
+ if [ "$debug_mode" = "true" ]; then
+ echo "❌ CRITICAL: Debug mode is enabled in production!"
+ echo " Set DEBUG=false immediately"
+ fi
+
+ # Verify mainnet configuration
+ if [ "$chain_id" = "1223953" ]; then
+ echo "⚠️ Using Radius Testnet in production environment"
+ echo " Switch to mainnet configuration if deploying to production"
+ fi
+
+ # Check for .env file
+ if [ -f ".env" ] && [ ! -f ".env.production" ]; then
+ echo "⚠️ Using .env file - ensure production values are set"
+ fi
+else
+ # Development environment reminders
+ echo "ℹ️ Environment: $env_mode"
+
+ if [ "$debug_mode" = "true" ]; then
+ echo "🔍 Debug mode enabled (OK for development)"
+ fi
+
+ if [ "$chain_id" = "1223953" ]; then
+ echo "🔗 Using Radius Testnet (Chain ID: 1223953)"
+ fi
+fi
+
+# Check for uncommitted changes
+if command -v git &> /dev/null; then
+ if [ -d ".git" ]; then
+ uncommitted=$(git status --porcelain 2>/dev/null | wc -l)
+ if [ "$uncommitted" -gt 0 ]; then
+ echo "📝 You have $uncommitted uncommitted change(s)"
+
+ # Check for changes to sensitive files
+ if git status --porcelain 2>/dev/null | grep -qE '\.env|private|secret|key'; then
+ echo "⚠️ Sensitive files may have been modified - review before committing"
+ fi
+ fi
+ fi
+fi
+
+# Token configuration summary
+if [ "$EVMAUTH_CONTRACT_ADDRESS" ]; then
+ echo "🔐 Token Gate Active:"
+ echo " Contract: ${EVMAUTH_CONTRACT_ADDRESS:0:10}...${EVMAUTH_CONTRACT_ADDRESS: -8}"
+ echo " Token ID: ${EVMAUTH_TOKEN_ID:-1}"
+fi
+
+# Server status check
+if lsof -i :3000 &>/dev/null; then
+ echo "✅ MCP Server running on port 3000"
+elif lsof -i :${PORT:-3000} &>/dev/null; then
+ echo "✅ MCP Server running on port ${PORT}"
+fi
+
+# Final reminders based on recent activity
+if [ -f "$HOME/.claude/logs/token-gate-$(date +%Y%m%d).log" ]; then
+ recent_fastmcp=$(grep -c "FastMCP" "$HOME/.claude/logs/token-gate-$(date +%Y%m%d).log" 2>/dev/null || echo 0)
+ recent_ngrok=$(grep -c "ngrok" "$HOME/.claude/logs/token-gate-$(date +%Y%m%d).log" 2>/dev/null || echo 0)
+
+ if [ "$recent_fastmcp" -gt 0 ] || [ "$recent_ngrok" -gt 0 ]; then
+ echo "📊 Today's activity: $recent_fastmcp FastMCP commands, $recent_ngrok ngrok sessions"
+ fi
+fi
+
+# Success message if everything looks good
+all_good=true
+[ "$env_mode" = "production" ] && [ "$debug_mode" = "true" ] && all_good=false
+[ "$uncommitted" -gt 0 ] && all_good=false
+
+if [ "$all_good" = true ] && [ "$env_mode" != "production" ]; then
+ echo "✨ Development environment properly configured!"
+fi
+
+exit 0 \ No newline at end of file
diff --git a/mcp-servers/token-gated-mcp-server/.claude/hooks/validate-token-config.sh b/mcp-servers/token-gated-mcp-server/.claude/hooks/validate-token-config.sh
new file mode 100755
index 0000000..f4c58bc
--- /dev/null
+++ b/mcp-servers/token-gated-mcp-server/.claude/hooks/validate-token-config.sh
@@ -0,0 +1,67 @@
+#!/bin/bash
+
+# Hook script to validate token configuration in TypeScript files
+# Used in PreToolUse hooks for Edit/Write operations
+
+# Parse the input JSON from CLAUDE_HOOK_DATA
+file_path=$(echo "$CLAUDE_HOOK_DATA" | jq -r '.tool_input.file_path // empty')
+content=$(echo "$CLAUDE_HOOK_DATA" | jq -r '.tool_input.content // .tool_input.new_string // ""')
+
+# Only process TypeScript files
+if [[ ! "$file_path" =~ \.(ts|tsx)$ ]]; then
+ exit 0
+fi
+
+# Check if content contains token configuration
+if echo "$content" | grep -qE 'contractAddress|chainId|tokenId|RadiusMcpSdk'; then
+ echo "🔐 Token configuration detected in $file_path"
+
+ # Validate contract address format (0x + 40 hex chars)
+ if echo "$content" | grep -qE '0x[a-fA-F0-9]{40}'; then
+ echo "✅ Valid contract address format"
+ else
+ if echo "$content" | grep -qE 'contractAddress.*0x'; then
+ echo "⚠️ Warning: Invalid contract address format detected"
+ echo " Contract addresses must be 0x followed by 40 hexadecimal characters"
+ fi
+ fi
+
+ # Check for Radius Testnet configuration
+ if echo "$content" | grep -q '1223953'; then
+ echo "✅ Configured for Radius Testnet (Chain ID: 1223953)"
+ fi
+
+ # Warn about debug mode
+ if echo "$content" | grep -qE 'debug:\s*true'; then
+ if [ "$NODE_ENV" = "production" ]; then
+ echo "❌ ERROR: Debug mode cannot be enabled in production!"
+ echo " Set debug: false or use process.env.NODE_ENV check"
+ exit 2 # Block the operation
+ else
+ echo "⚠️ Warning: Debug mode is enabled - disable before production"
+ fi
+ fi
+
+ # Check for hardcoded private keys (security check)
+ if echo "$content" | grep -qE '0x[a-fA-F0-9]{64}'; then
+ echo "🚨 SECURITY WARNING: Possible private key detected!"
+ echo " Never commit private keys to source control"
+ echo " Use environment variables instead"
+ # exit 2 # Uncomment to block operation if private key detected
+ fi
+
+ # Validate token protection pattern
+ if echo "$content" | grep -q 'radius.protect'; then
+ echo "✅ Token protection implemented"
+
+ # Check if __evmauth is in parameters
+ if echo "$content" | grep -q '__evmauth.*z\.any'; then
+ echo "✅ __evmauth parameter included in schema"
+ else
+ echo "⚠️ Reminder: Include __evmauth in tool parameters:"
+ echo " __evmauth: z.any().optional()"
+ fi
+ fi
+fi
+
+exit 0 \ No newline at end of file
diff --git a/mcp-servers/token-gated-mcp-server/.claude/settings.json b/mcp-servers/token-gated-mcp-server/.claude/settings.json
new file mode 100644
index 0000000..b14848c
--- /dev/null
+++ b/mcp-servers/token-gated-mcp-server/.claude/settings.json
@@ -0,0 +1,119 @@
+{
+ "permissions": {
+ "allow": [
+ "Read",
+ "Write",
+ "Edit",
+ "MultiEdit",
+ "Grep",
+ "Glob",
+ "LS",
+ "NotebookEdit",
+ "NotebookRead",
+ "TodoWrite",
+ "WebSearch",
+ "WebFetch",
+ "Bash(npm run dev*)",
+ "Bash(npm run build*)",
+ "Bash(npm run test*)",
+ "Bash(npm run lint*)",
+ "Bash(npm run typecheck*)",
+ "Bash(npm install*)",
+ "Bash(npm ci*)",
+ "Bash(npx tsx*)",
+ "Bash(npx fastmcp*)",
+ "Bash(ngrok http*)",
+ "Bash(git status*)",
+ "Bash(git diff*)",
+ "Bash(git log*)",
+ "Bash(git add*)",
+ "Bash(git commit*)",
+ "Bash(curl https://rpc.testnet.radiustech.xyz*)",
+ "Bash(echo $EVMAUTH*)",
+ "Bash(docker build*)",
+ "Bash(docker run*)"
+ ],
+ "deny": [
+ "Read(**/*private*key*)",
+ "Read(**/*.env.production)",
+ "Read(**/*secret*)",
+ "Write(**/*private*key*)",
+ "Write(**/*.env.production)",
+ "Write(**/*secret*)",
+ "Bash(rm -rf*)",
+ "Bash(npm publish*)",
+ "Bash(curl -X POST*)",
+ "Bash(curl -X PUT*)",
+ "Bash(curl -X DELETE*)"
+ ],
+ "additionalDirectories": []
+ },
+ "env": {
+ "EVMAUTH_CONTRACT_ADDRESS": "0x5448Dc20ad9e0cDb5Dd0db25e814545d1aa08D96",
+ "EVMAUTH_CHAIN_ID": "1223953",
+ "EVMAUTH_RPC_URL": "https://rpc.testnet.radiustech.xyz",
+ "EVMAUTH_TOKEN_ID": "1",
+ "NODE_ENV": "development",
+ "DEBUG": "false",
+ "RADIUS_TESTNET": "true"
+ },
+ "hooks": {
+ "PreToolUse": [
+ {
+ "matcher": "Edit|MultiEdit|Write",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "#!/bin/bash\nfile_path=$(echo \"$CLAUDE_HOOK_DATA\" | jq -r '.tool_input.file_path // empty')\nif [[ \"$file_path\" == *.ts || \"$file_path\" == *.tsx ]]; then\n # Check if we're writing token configuration\n if echo \"$CLAUDE_HOOK_DATA\" | jq -r '.tool_input.content // .tool_input.new_string // \"\"' | grep -q 'contractAddress\\|chainId\\|tokenId'; then\n echo \"🔐 Token configuration detected - validating...\"\n # Validate contract address format\n if echo \"$CLAUDE_HOOK_DATA\" | grep -q '0x[a-fA-F0-9]\\{40\\}'; then\n echo \"✅ Valid contract address format\"\n else\n echo \"⚠️ Warning: Invalid contract address format detected\"\n fi\n fi\nfi"
+ }
+ ]
+ },
+ {
+ "matcher": "Bash",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "#!/bin/bash\ncommand=$(echo \"$CLAUDE_HOOK_DATA\" | jq -r '.tool_input.command')\n# Log FastMCP and ngrok commands for debugging\nif [[ \"$command\" == *\"fastmcp\"* ]] || [[ \"$command\" == *\"ngrok\"* ]]; then\n echo \"[Token-Gate Debug] Running: $command\" >> ~/.claude/token-gate-debug.log\nfi"
+ }
+ ]
+ }
+ ],
+ "PostToolUse": [
+ {
+ "matcher": "Edit|MultiEdit|Write",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "#!/bin/bash\nfile_path=$(echo \"$CLAUDE_HOOK_DATA\" | jq -r '.tool_input.file_path // empty')\n# Auto-format TypeScript files\nif [[ \"$file_path\" == *.ts || \"$file_path\" == *.tsx ]]; then\n if command -v npx &> /dev/null && [ -f \"package.json\" ]; then\n npx prettier --write \"$file_path\" 2>/dev/null || true\n fi\nfi\n# Validate token-gating implementation\nif [[ \"$file_path\" == *server.ts* ]] || [[ \"$file_path\" == *index.ts* ]]; then\n if grep -q 'radius.protect' \"$file_path\"; then\n echo \"✅ Token protection detected in $file_path\"\n fi\nfi"
+ }
+ ]
+ }
+ ],
+ "Stop": [
+ {
+ "matcher": "",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "#!/bin/bash\n# Check if debug mode is still enabled\nif [ \"$DEBUG\" = \"true\" ]; then\n echo \"⚠️ Reminder: Debug mode is enabled. Disable before production deployment!\"\nfi\n# Check if using testnet\nif [ \"$RADIUS_TESTNET\" = \"true\" ]; then\n echo \"ℹ️ Using Radius Testnet (Chain ID: 1223953)\"\nfi"
+ }
+ ]
+ }
+ ]
+ },
+ "statusLine": {
+ "type": "command",
+ "command": "#!/bin/bash\necho \"🔐 Token-Gated MCP | Chain: ${EVMAUTH_CHAIN_ID:-1223953} | Token: ${EVMAUTH_TOKEN_ID:-1} | ${NODE_ENV:-dev}\""
+ },
+ "model": "claude-3-5-sonnet-20241022",
+ "includeCoAuthoredBy": true,
+ "cleanupPeriodDays": 30,
+ "_metadata": {
+ "name": "Token-Gated MCP Server",
+ "version": "1.0.0",
+ "category": "mcp-server",
+ "generated": "2025-08-20T13:36:56.498Z",
+ "generator": "manual",
+ "note": "Official Claude Code configuration"
+ }
+}