<div align="center">
  <a href="https://github.com/modelcontextprotocol-identity/xmcp-i">
    <picture>
      <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/modelcontextprotocol-identity/xmcp-i/main/assets/mcp-i-logo-dark.png">
      <img alt="MCP-I logo" src="https://raw.githubusercontent.com/modelcontextprotocol-identity/xmcp-i/main/assets/mcp-i-logo-light.png" height="128">
    </picture>
  </a>
  <h1>@kya-os/mcp-i</h1>

<a href="https://github.com/modelcontextprotocol-identity/xmcp-i"><img alt="MCP-I" src="https://img.shields.io/badge/MCP--I-000000.svg?style=for-the-badge&labelColor=000"></a>
<a href="https://www.npmjs.com/package/@kya-os/mcp-i"><img alt="NPM version" src="https://img.shields.io/npm/v/@kya-os/mcp-i.svg?style=for-the-badge&labelColor=000000"></a>
<a href="https://github.com/modelcontextprotocol-identity/xmcp-i/blob/main/license.md"><img alt="License" src="https://img.shields.io/npm/l/@kya-os/mcp-i.svg?style=for-the-badge&labelColor=000000"></a>

</div>

## Node.js Runtime for MCP-I

`@kya-os/mcp-i` is the Node.js implementation of the MCP-I (Model Context Protocol with Identity) framework. It provides identity management, cryptographic proof generation, session handling, and delegation verification for building secure AI agents.

## Quick Start

### For New Projects

Use the scaffolding tool to create a new MCP-I project:

```bash
npx @kya-os/create-mcpi-app my-agent
cd my-agent
npm run dev
```

### For Existing Projects

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

## Core Features

- **Identity Management** - Ed25519 key generation and DID-based identity
- **Cryptographic Proofs** - JWS proof generation for tool responses
- **Session Management** - Nonce-protected sessions with configurable TTL
- **Delegation Verification** - Verify delegated permissions from AgentShield
- **Tool Protection** - Configure which tools require delegation
- **Canonical Audit Trails** - Record privacy-minimal lifecycle events through `@kya-os/mcp`
- **Well-Known Endpoints** - Standard MCP-I discovery endpoints

## API Reference

### CLI Identity Setup

Initialize identity for CLI tools and development:

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

const result = await enableMCPIdentityCLI({
  name: "my-agent",
  description: "My AI agent with identity",
  onProgress: (event) => {
    console.log(`${event.stage}: ${event.message}`);
  },
});

console.log(`Agent DID: ${result.identity.did}`);
console.log(`Claim URL: ${result.metadata.claimUrl}`);
```

**Options:**

| Option | Type | Description |
|--------|------|-------------|
| `name` | `string` | Agent name for registration |
| `description` | `string` | Agent description |
| `repository` | `string` | Git repository URL |
| `endpoint` | `string` | KTA endpoint (default: `https://knowthat.ai`) |
| `logLevel` | `'silent' \| 'info' \| 'debug'` | Logging verbosity |
| `onProgress` | `(event) => void` | Progress callback |
| `skipRegistration` | `boolean` | Skip KTA registration |

### Identity Manager

Direct identity management for runtime use:

```typescript
import { IdentityManager, type AgentIdentity } from "@kya-os/mcp-i";

const manager = new IdentityManager({
  environment: "development",
  devIdentityPath: ".mcpi/identity.json",
});

// Load or generate identity
const identity: AgentIdentity = await manager.ensureIdentity();

console.log(identity.did);       // did:key:z6Mk...
console.log(identity.publicKey); // Base64-encoded Ed25519 public key
```

### MCP-I Runtime

Create a full MCP-I runtime with all providers:

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

const runtime = createMCPIRuntime({
  identity: {
    environment: "production",
  },
  session: {
    timestampSkewSeconds: 120,
    sessionTtlMinutes: 30,
  },
  // Optional RuntimeAuditConfig backed by @kya-os/mcp's canonical trail.
  auditTrail,
});

// Handle MCP handshake
const handshakeResult = await runtime.handleHandshake(request);

// Process tool calls with proof generation
const result = await runtime.processToolCall(
  toolName,
  args,
  handler,
  sessionContext
);
```

### Delegation Verification

Verify delegated permissions:

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

const verifier = createDelegationVerifier({
  agentShieldApiUrl: "https://kya.vouched.id",
  agentShieldApiKey: process.env.AGENTSHIELD_API_KEY,
});

const result = await verifier.verify({
  delegationToken: token,
  requiredScopes: ["checkout:execute"],
  agentDid: runtime.getIdentity().did,
});

if (result.valid) {
  console.log("Delegation verified:", result.delegationId);
}
```

### Tool Protection

Configure which tools require delegation:

```typescript
import {
  ToolProtectionResolver,
  AgentShieldToolProtectionSource
} from "@kya-os/mcp-i";

// Load protection config from AgentShield
const source = new AgentShieldToolProtectionSource({
  apiUrl: "https://kya.vouched.id",
  apiKey: process.env.AGENTSHIELD_API_KEY,
  projectId: process.env.AGENTSHIELD_PROJECT_ID,
});

const resolver = new ToolProtectionResolver([source]);
const protection = await resolver.getProtection("checkout");

if (protection?.requiresDelegation) {
  // Tool requires valid delegation token
}
```

### Proof Generation

Generate cryptographic proofs for tool responses:

```typescript
import { ProofGenerator, createProofResponse } from "@kya-os/mcp-i";

const proofGenerator = new ProofGenerator(identity, cryptoProvider);

const proof = await proofGenerator.generateProof(
  { method: "get-weather", params: { city: "London" } },
  { data: { temperature: 20 } },
  session, // SessionContext, e.g. { sessionId, nonce, audience }
);

// Create response with detached proof
const response = createProofResponse(toolOutput, proof);
```

### Session Management

Handle MCP sessions with nonce protection:

```typescript
import { SessionManager, createHandshakeRequest } from "@kya-os/mcp-i";

const sessionManager = new SessionManager({
  timestampSkewSeconds: 120,
  ttlMinutes: 30,
});

// Create handshake request
const request = createHandshakeRequest({
  clientDid: "did:key:z6Mk...",
  timestamp: Date.now(),
  nonce: crypto.randomUUID(),
});

// Validate and create session
const session = await sessionManager.createSession(request);
```

### Well-Known Endpoints

Create standard MCP-I discovery endpoints:

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

const handler = createWellKnownHandler({
  identity,
  serverUrl: "https://my-agent.example.com",
});

// Handle requests to:
// - /.well-known/mcp-identity/health
// - /.well-known/mcp-identity/self
// - /.well-known/did.json
const response = await handler(pathname);
```

## Nonce Cache

Prevent replay attacks with nonce caching:

```typescript
import {
  MemoryNonceCache,
  RedisNonceCache,
  DynamoDBNonceCache,
  CloudflareKVNonceCache,
} from "@kya-os/mcp-i";

// In-memory (development)
const cache = new MemoryNonceCache({ maxSize: 10000 });

// Redis (production)
const cache = new RedisNonceCache({ url: process.env.REDIS_URL });

// DynamoDB (AWS)
const cache = new DynamoDBNonceCache({ tableName: "nonce-cache" });
```

## Test Infrastructure

For testing MCP-I integrations:

```typescript
import {
  createTestEnvironment,
  MockIdentityProvider,
  deterministicKeys,
} from "@kya-os/mcp-i/test";

// Set XMCP_ENV=test to enable
const testEnv = await createTestEnvironment({
  seed: "test-seed-123",
});

// Deterministic keys for reproducible tests
const identity = await deterministicKeys.generateIdentity("test-agent");
```

## Environment Variables

| Variable | Description |
|----------|-------------|
| `AGENT_PRIVATE_KEY` | Base64-encoded Ed25519 private key (production) |
| `AGENT_KEY_ID` | Key ID for the agent |
| `AGENT_DID` | Agent's DID (production) |
| `AGENTSHIELD_API_KEY` | API key for AgentShield |
| `AGENTSHIELD_API_URL` | AgentShield API URL (default: `https://kya.vouched.id`) |
| `AGENTSHIELD_PROJECT_ID` | Project ID in AgentShield |
| `XMCP_ENV` | Set to `test` to enable test infrastructure |

## Platform Support

This package is for **Node.js** environments. For other platforms:

| Platform | Package |
|----------|---------|
| Cloudflare Workers | `@kya-os/mcp-i-cloudflare` |
| Platform-agnostic core | `@kya-os/mcp-i-core` |

## CLI Tools

Use the `@kya-os/cli` package for command-line operations:

```bash
npm install -g @kya-os/cli

# Initialize identity
mcpi init

# Check identity status
mcpi check

# Rotate keys
mcpi rotate
```

## Related Packages

- [`@kya-os/create-mcpi-app`](https://www.npmjs.com/package/@kya-os/create-mcpi-app) - Project scaffolding
- [`@kya-os/mcp-i-cloudflare`](https://www.npmjs.com/package/@kya-os/mcp-i-cloudflare) - Cloudflare Workers runtime
- [`@kya-os/mcp-i-core`](https://www.npmjs.com/package/@kya-os/mcp-i-core) - Platform-agnostic core
- [`@kya-os/cli`](https://www.npmjs.com/package/@kya-os/cli) - CLI tools
- [`@kya-os/contracts`](https://www.npmjs.com/package/@kya-os/contracts) - Shared types and schemas

## Learn More

- [MCP-I Documentation](https://github.com/modelcontextprotocol-identity/xmcp-i) - Full framework documentation
- [Model Context Protocol](https://modelcontextprotocol.io) - Core protocol specification
- [Know That AI](https://knowthat.ai) - Agent registration and claims

## License

MIT License - see [LICENSE](https://github.com/modelcontextprotocol-identity/xmcp-i/blob/main/license.md)
