# @kya-os/mcp-i

The SEO package for AI agents. Register your MCP server and get automatic directory listings in 2 lines of code.

Note: This package is alpha release, do not use in production.
v1.0.0 will be released this week.

[![npm version](https://img.shields.io/npm/v/@kya-os/mcp-i.svg)](https://www.npmjs.com/package/@kya-os/mcp-i)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![MCP-I Conformance](https://img.shields.io/badge/MCP--I-Level%202-green)](https://modelcontextprotocol-identity.io)

## Why Your MCP Server Needs This

**For MCP Server Developers:**

- **Get a DID** - Your agent gets a permanent, cryptographic identity from knowthat.ai
- **Automatic Directory Listings** - Submit to multiple directories with zero extra work
- **Build Reputation** - Every interaction is signed and verifiable
- **Future-Proof** - Ready for the decentralized agent ecosystem
- **Production-Ready** - Optimized for Lambda, Edge, Next.js, and traditional deployments
- **Fast Registration** - New CLI endpoint provides 100-200ms registration (10-50x faster!)

**For Directory Maintainers:**

- **Easy Integration** - List MCP-I compliant agents automatically
- **Verified Agents** - Only list agents with cryptographic proof
- **Join the Network** - Tap into the growing MCP-I ecosystem

## How It Works

1. **Identity Registration**: Your agent is registered with knowthat.ai (the MCP-I registry)
2. **DID Generation**: You get a `did:web:knowthat.ai:agents:your-agent` identifier
3. **Directory Submission**: Based on your preferences, knowthat.ai submits your agent to directories
4. **Cryptographic Signing**: All agent responses are signed with your private key
5. **Verification**: Anyone can verify your agent's identity and authenticity

## Installation

```bash
npm install @kya-os/mcp-i
```

## Quick Start

### 1. Zero Configuration (Recommended)

```typescript
import "@kya-os/mcp-i/auto";
// That's it! Your server now has cryptographic identity
```

### 2. With Progress Tracking (CLI Tools)

```typescript
import { enableMCPIdentity } from "@kya-os/mcp-i";

const identity = await enableMCPIdentity({
  name: "My CLI Tool",
  // Progress callback automatically triggers fast CLI endpoint (100-200ms)
  onProgress: (event) => {
    console.log(`${event.stage}: ${event.message}`);
  }
});
```

### 3. Production Configuration

```typescript
import { enableMCPIdentity } from "@kya-os/mcp-i";

const identity = await enableMCPIdentity({
  name: "Production Agent",

  // Auto-detect runtime (Lambda, Edge, Node.js)
  storage: "auto",
  transport: "auto",

  // Encrypt private keys at rest
  encryptionPassword: process.env.AGENT_KEY_PASSWORD,

  // Professional logging
  logLevel: "error", // or 'silent' for production

  // Directory preferences (optional)
  directories: "verified", // List on all verified directories
  // OR directories: ["smithery", "glama"] // Specific directories
  // OR directories: "none" // No directory listings
});

// Enable automatic key rotation
await identity.enableAutoRotation({
  maxAge: 90 * 24 * 60 * 60 * 1000, // 90 days
  maxSignatures: 1_000_000, // 1M signatures
});
```

### 3. Lambda/Edge Runtime

```typescript
// Automatic configuration for serverless
const identity = await enableMCPIdentity({
  name: "Serverless Agent",
  storage: "memory", // No file system needed
  transport: "fetch", // Native fetch for edge
  logLevel: "silent", // No console output
});
```

## Production Features

### Performance Optimizations

- **Lazy Loading**: Crypto libraries load only when needed
- **Signature Caching**: Repeated signatures are 10x faster
- **Precomputed Values**: DIDs and keys cached in memory
- **Optimized Transport**: Auto-selects axios vs fetch

### Security Features

- **Key Encryption**: Private keys encrypted with AES-256-GCM
- **Key Rotation**: Automatic rotation based on age/usage
- **Nonce Tracking**: Prevents replay attacks
- **Timestamp Validation**: Configurable tolerance windows

### Runtime Support

- **AWS Lambda**: Automatic memory storage
- **Vercel Edge**: Native fetch transport
- **Cloudflare Workers**: Full compatibility
- **Node.js**: Traditional file storage

### Directory Listings

```typescript
// Configure directory listings
await enableMCPIdentity({
  name: "My Agent",

  // Option 1: List on all verified directories
  directories: "verified",

  // Option 2: List on specific directories
  directories: ["smithery", "glama"],

  // Option 3: No directory listings (registry only)
  directories: "none",
});

// Directory preferences are sent to knowthat.ai
// The registry handles submissions to your chosen directories
```

## Advanced Usage

### Key Rotation

```typescript
// Check key health
const health = identity.checkKeyHealth();
console.log(`Key age: ${health.age}ms`);
console.log(`Signatures: ${health.signatureCount}`);
console.log(`Should rotate: ${health.shouldRotate}`);

// Manual rotation
const result = await identity.rotateKeys("security-policy");
if (result.success) {
  console.log(`Grace period ends: ${result.gracePeriodEnd}`);
}

// Automatic rotation
await identity.enableAutoRotation({
  maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days
  maxSignatures: 500_000, // 500k signatures
});
```

### Edit/Claim URLs

```typescript
// Get signed URLs for editing
const { editUrl, claimUrl } = await identity.requestEditAccess();

// Edit URL - for existing agents
console.log("Edit your agent:", editUrl);

// Claim URL - for draft/unclaimed agents
console.log("Claim your agent:", claimUrl);
```

### Custom Storage

```typescript
// Encrypted file storage
await enableMCPIdentity({
  storage: "file",
  persistencePath: "/secure/location/.identity",
  encryptionPassword: "strong-password",
});

// Memory storage with custom key
await enableMCPIdentity({
  storage: "memory",
  memoryKey: "agent-123", // Useful for multiple agents
});
```

### Custom Logger

```typescript
await enableMCPIdentity({
  logger: {
    debug: (msg, ...args) => myLogger.debug(msg, args),
    info: (msg, ...args) => myLogger.info(msg, args),
    warn: (msg, ...args) => myLogger.warn(msg, args),
    error: (msg, ...args) => myLogger.error(msg, args),
  },
});
```

## API Reference

### `enableMCPIdentity(options?)`

Main function to enable identity for your MCP server.

**Options:**

```typescript
interface MCPIdentityOptions {
  // Basic info
  name?: string;
  description?: string;
  repository?: string;

  // Storage
  storage?: "file" | "memory" | "auto";
  persistencePath?: string;
  memoryKey?: string;
  encryptionPassword?: string;

  // Transport
  transport?: "axios" | "fetch" | "auto";

  // Security
  timestampTolerance?: number; // Default: 60000ms
  enableNonceTracking?: boolean; // Default: true

  // Directory listings
  directories?: string[] | "verified" | "none"; // Default: "verified"

  // Development
  mode?: "development" | "production";

  // Logging
  logger?: Logger;
  logLevel?: "debug" | "info" | "warn" | "error" | "silent";
}
```

### `MCPIdentity` Methods

- `sign(message)`: Sign with caching
- `verify(message, signature, publicKey?)`: Verify signatures
- `respondToChallenge(challenge)`: MCP-I authentication
- `signResponse(response)`: Add identity to responses
- `requestEditAccess()`: Get edit/claim URLs
- `rotateKeys(reason?)`: Manual key rotation
- `enableAutoRotation(policy?)`: Automatic rotation
- `checkKeyHealth()`: Key rotation status

## Files Created

```
.mcp-identity.json    # Your agent's identity (encrypted if password set)
```

## Security Best Practices

1. **Use encryption in production**: Always set `encryptionPassword`
2. **Enable key rotation**: Set up automatic rotation policies
3. **Secure storage**: Use appropriate file permissions
4. **Monitor key health**: Check rotation status regularly
5. **Add to .gitignore**: Never commit identity files

## Performance Tips

1. **Use memory storage** for Lambda/Edge runtimes
2. **Enable signature caching** (automatic)
3. **Use 'silent' log level** in production
4. **Let transport auto-select** based on runtime
5. **Preload identity** during cold starts

## Troubleshooting

### Lambda/Edge Issues

- Ensure `storage: 'memory'` or `'auto'`
- Use `transport: 'fetch'` for edge runtimes
- Set `logLevel: 'silent'` to avoid console issues

### Key Rotation Failures

- Check network connectivity to knowthat.ai
- Verify current keys are not corrupted
- Manual rotation: `await identity.rotateKeys('recovery')`

### Performance Issues

- Verify signature caching is working
- Check lazy loading (should see delayed first signature)
- Use memory storage when possible

## License

MIT
