npm package: @kya-os/mcp-i-core
Description: Core runtime and types for MCP-I framework
Author: Dylan Hobbs
Latest version: 1.6.2

# @kya-os/mcp-i-core

Platform-agnostic core for MCP-I (Model Context Protocol with Identity) runtime. This package provides the shared business logic, interfaces, and abstractions that work across all JavaScript environments.

## Overview

`@kya-os/mcp-i-core` is the foundation for building MCP-I runtimes on any platform. It provides:

- **Isomorphic verification logic** that works across Node.js, Cloudflare Workers, Vercel Edge, and browsers
- **Provider-based architecture** for platform-specific implementations
- **Multiple proof formats** (JWT-VC, Data Integrity, DetachedJWS)
- **DID resolution** with pluggable resolvers
- **Progressive verification** for optimal performance
- **Credential and delegation** support
- **Transparent security** - LLMs never see cryptographic proofs

### Security Model

MCP-I implements **transparent security** - authentication and proof generation happen at the protocol layer, completely invisible to language models (LLMs).

**What LLMs see:**
```json
{
  "content": [
    { "type": "text", "text": "Business data here" }
  ]
}
```

**What verification services see:**
```json
{
  "data": { "content": [...] },
  "proof": {
    "did": "did:key:z6Mkh...",
    "signature": "ey4a9s...",
    "nonce": "x7f2b..."
  }
}
```

The runtime automatically extracts proofs and sends them to verifier services. This keeps:
- **LLM context efficient** - No cryptographic data in prompts
- **Privacy maintained** - Private keys never exposed to AI
- **Security separate** - Authentication independent of business logic

See [MCP_I_RESPONSE_SPEC.md](../../MCP_I_RESPONSE_SPEC.md) for complete details on response structure and proof handling.

## Architecture

```
┌─────────────────────────────────────────────────────────────┐
│                      Application Layer                       │
│         (@kya-os/mcp-i or @kya-os/mcp-i-cloudflare)         │
└────────────────────┬────────────────────────────────────────┘
                     │
┌────────────────────▼────────────────────────────────────────┐
│                    @kya-os/mcp-i-core                       │
│                                                              │
│  ┌─────────────┐  ┌──────────────┐  ┌──────────────────┐  │
│  │   Runtime   │  │ ProofEngine  │  │  DID Resolver    │  │
│  │    Base     │  │              │  │                  │  │
│  └─────────────┘  └──────────────┘  └──────────────────┘  │
│                                                              │
│  ┌─────────────┐  ┌──────────────┐  ┌──────────────────┐  │
│  │ Credential  │  │  Delegation  │  │   Progressive    │  │
│  │  Verifier   │  │   Registry   │  │    Verifier     │  │
│  └─────────────┘  └──────────────┘  └──────────────────┘  │
└────────────────────┬────────────────────────────────────────┘
                     │
┌────────────────────▼────────────────────────────────────────┐
│                    Provider Interfaces                       │
│                                                              │
│  ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────────┐  │
│  │  Crypto  │ │ Identity │ │  Clock   │ │    Fetch     │  │
│  │ Provider │ │ Provider │ │ Provider │ │   Provider   │  │
│  └──────────┘ └──────────┘ └──────────┘ └──────────────┘  │
│                                                              │
│  ┌──────────┐ ┌──────────┐ ┌──────────────────────────┐   │
│  │ Storage  │ │  Nonce   │ │   Platform-Specific      │   │
│  │ Provider │ │  Cache   │ │    Implementations       │   │
│  └──────────┘ └──────────┘ └──────────────────────────┘   │
└──────────────────────────────────────────────────────────────┘
```

## Installation

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

## Provider Interfaces

### CryptoProvider
Handles all cryptographic operations (signing, verification, key generation).

```typescript
abstract class CryptoProvider {
  abstract sign(data: Uint8Array, privateKey: string): Promise<Uint8Array>;
  abstract verify(data: Uint8Array, signature: Uint8Array, publicKey: string): Promise<boolean>;
  abstract generateKeyPair(): Promise<{ privateKey: string; publicKey: string }>;
  abstract hash(data: Uint8Array): Promise<Uint8Array>;
}
```

### IdentityProvider
Manages agent identity storage and retrieval.

```typescript
abstract class IdentityProvider {
  abstract loadIdentity(): Promise<AgentIdentity | null>;
  abstract storeIdentity(identity: AgentIdentity): Promise<void>;
  abstract hasIdentity(): Promise<boolean>;
  abstract deleteIdentity(): Promise<void>;
}
```

### ClockProvider
Provides deterministic time operations for testing and consistency.

```typescript
abstract class ClockProvider {
  abstract now(): number;
  abstract isWithinSkew(timestamp: number, skewSeconds: number): boolean;
  abstract hasExpired(expiresAt: number): boolean;
  abstract calculateExpiry(ttlSeconds: number): number;
}
```

### FetchProvider
Handles network operations for DID resolution and verification.

```typescript
abstract class FetchProvider {
  abstract resolveDID(did: string): Promise<any>;
  abstract fetchStatusList(url: string): Promise<any>;
  abstract fetchDelegationChain(id: string): Promise<any[]>;
  abstract fetch(url: string, options?: any): Promise<Response>;
}
```

## Core Components

### MCPIRuntimeBaseV2

The main runtime class that orchestrates all MCP-I operations.

```typescript
import { MCPIRuntimeBaseV2 } from '@kya-os/mcp-i-core';

class MyPlatformRuntime extends MCPIRuntimeBaseV2 {
  constructor() {
    super({
      cryptoProvider: new MyeCryptoProvider(),
      identityProvider: new MyIdentityProvider(),
      storageProvider: new MyStorageProvider(),
      nonceCacheProvider: new MyNonceCacheProvider(),
      clockProvider: new MyClockProvider(),
      fetchProvider: new MyFetchProvider()
    });
  }

  // Platform-specific implementations
  protected async generateSessionId(): Promise<string> {
    // Use platform's secure random
  }

  protected async generateNonce(): Promise<string> {
    // Use platform's secure random
  }
}
```

### ProofEngine

Supports multiple proof formats with a unified interface.

```typescript
const proofEngine = new DefaultProofEngine(cryptoProvider);

// Create proof in different formats
const jwtProof = await proofEngine.createProof(data, privateKey, {
  format: { type: 'JWT-VC', algorithm: 'EdDSA' }
});

const dataIntegrityProof = await proofEngine.createProof(data, privateKey, {
  format: { type: 'DataIntegrity', algorithm: 'Ed25519Signature2020' }
});

// Verify any format
const result = await proofEngine.verifyProof(data, proof, publicKey, {
  format: { type: 'DetachedJWS', algorithm: 'Ed25519' }
});
```

### DID Resolver

Pluggable DID resolution with built-in support for did:key and did:web.

```typescript
const resolver = new UniversalDIDResolver(fetchProvider);

// Register custom resolver
resolver.registerResolver(new MyCustomDIDResolver());

// Resolve any DID
const document = await resolver.resolve('did:key:z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK');
const publicKey = await resolver.getPublicKey(did, keyId);
```

### Progressive Verification

Optimized verification with offline and online stages.

```typescript
const verifier = new ProgressiveVerifier(credentialVerifier, delegationRegistry);

// Stage-1: Quick offline checks
// Stage-2: Full online verification (parallel)
const result = await verifier.verifyProgressive(data, {
  verifyCredential: true,
  checkRevocation: true,
  maxChainDepth: 5
});
```

## Platform Implementations

### Node.js / Vercel
```typescript
// @kya-os/mcp-i
import { MCPIRuntimeBaseV2 } from '@kya-os/mcp-i-core';
import { NodeCryptoProvider } from './providers/node-crypto';
import { FileSystemIdentityProvider } from './providers/fs-identity';

export class MCPIRuntime extends MCPIRuntimeBaseV2 {
  constructor() {
    super({
      cryptoProvider: new NodeCryptoProvider(),
      identityProvider: new FileSystemIdentityProvider(),
      // ... other Node.js providers
    });
  }
}
```

### Cloudflare Workers
```typescript
// @kya-os/mcp-i-cloudflare
import { MCPIRuntimeBaseV2 } from '@kya-os/mcp-i-core';
import { WebCryptoProvider } from './providers/web-crypto';
import { KVIdentityProvider } from './providers/kv-identity';

export class MCPICloudflareRuntime extends MCPIRuntimeBaseV2 {
  constructor(env: CloudflareEnv) {
    super({
      cryptoProvider: new WebCryptoProvider(),
      identityProvider: new KVIdentityProvider(env),
      // ... other Cloudflare providers
    });
  }
}
```

## Isomorphic Verification

The verification logic works identically across all platforms:

```typescript
// Works in Node.js, Cloudflare Workers, Vercel Edge, Browser
async function verifyMCPIProof(data: any, proof: any): Promise<boolean> {
  const runtime = createRuntimeForPlatform(); // Platform-specific
  return runtime.verifyProof(data, proof); // Isomorphic logic
}
```

## Security Considerations

1. **Private Keys**: Never stored in core, always handled by IdentityProvider
2. **Nonce Management**: Automatic replay attack prevention
3. **Time Skew**: Configurable tolerance for clock differences
4. **Session Lifecycle**: Absolute lifetime limits
5. **Audit Logging**: Built-in audit trail support

### Progressive Verification

**Signature verification requires a DID resolver and signature verifier.** If neither is configured, signature checks are skipped and the credential is treated as structurally valid. This is intentional for environments where DID resolution is not available (e.g., offline operation, testing, or edge deployments without network access).

In production deployments, always configure a DID resolver to enable full cryptographic verification:

```typescript
const verifier = new DelegationCredentialVerifier({
  resolveDID: async (did) => fetchDIDDocument(did),
  verifySignature: async (vc, publicKey) => verifyEd25519(vc, publicKey),
  resolveStatusList: async (url) => fetchStatusList(url),
});
```

## Testing

The provider-based architecture makes testing straightforward:

```typescript
import { MockCryptoProvider, MockIdentityProvider } from '@kya-os/mcp-i-core/test';

const runtime = new MCPIRuntimeBaseV2({
  cryptoProvider: new MockCryptoProvider(),
  identityProvider: new MockIdentityProvider(),
  // ... mock providers
});

// Test business logic without platform dependencies
```

## Migration Guide

### From @kya-os/mcp-i v1.x

The existing API remains unchanged. Internal implementation now uses core:

```typescript
// Before (still works)
import { MCPIRuntime } from '@kya-os/mcp-i';
const runtime = new MCPIRuntime();

// After (also works, same API)
import { MCPIRuntime } from '@kya-os/mcp-i';
const runtime = new MCPIRuntime();
```

### For New Projects

Use the platform-specific package:

```typescript
// Node.js / Vercel
import { createMCPIServer } from '@kya-os/mcp-i';

// Cloudflare Workers
import { createMCPIServer } from '@kya-os/mcp-i-cloudflare';
```

## Contributing

See [CONTRIBUTING.md](../../CONTRIBUTING.md) for development setup and guidelines.

## License

MIT